Easy Tutorial
❮ Perl Redo Statement Perl Socket Programming ❯

Perl Directory Operations

Below are some standard functions for directory operations:

opendir DIRHANDLE, EXPR  # Open directory
readdir DIRHANDLE        # Read directory
rewinddir DIRHANDLE      # Reset pointer to the beginning
telldir DIRHANDLE        # Return current position in directory
seekdir DIRHANDLE, POS   # Set pointer to POS in directory
closedir DIRHANDLE       # Close directory

Display All Files

To display all files in a directory, the following example uses the glob operator:

Example

#!/usr/bin/perl

# Display all files in the /tmp directory
$dir = "/tmp/*";
my @files = glob( $dir );

foreach (@files ){
   print $_ . "\n";
}

# Display all files ending with .c in the /tmp directory
$dir = "/tmp/*.c";
@files = glob( $dir );

foreach (@files ){
   print $_ . "\n";
}

# Display all hidden files in the /tmp directory
$dir = "/tmp/.*";
@files = glob( $dir );
foreach (@files ){
   print $_ . "\n";
}

# Display all files in the /tmp and /home directories
$dir = "/tmp/* /home/*";
@files = glob( $dir );

foreach (@files ){
   print $_ . "\n";
}

The following example lists all files in the current directory:

Example

#!/usr/bin/perl

opendir (DIR, '.') or die "Cannot open directory, $!";
while ($file = readdir DIR) {
  print "$file\n";
}
closedir DIR;

To display all files ending with .c in the /tmp directory, you can use the following code:

Example

#!/usr/bin/perl

opendir(DIR, '.') or die "Cannot open directory, $!";
foreach (sort grep(/^.*\.c$/, readdir(DIR))){
   print "$_\n";
}
closedir DIR;

Create a New Directory

We can use the mkdir function to create a new directory, provided you have sufficient permissions:

Example

#!/usr/bin/perl

$dir = "/tmp/perl";

# Create a perl directory under the /tmp directory
mkdir( $dir ) or die "Cannot create $dir directory, $!";
print "Directory created successfully\n";

Delete a Directory

We can use the rmdir function to delete a directory, provided you have sufficient permissions. The directory to be deleted must be empty:

Example

#!/usr/bin/perl

$dir = "/tmp/perl";

# Delete the perl directory under the /tmp directory
rmdir( $dir ) or die "Cannot delete $dir directory, $!";
print "Directory deleted successfully\n";

Change Directory

We can use the chdir function to change the current directory, provided you have sufficient permissions. Here is an example:

Example

#!/usr/bin/perl

$dir = "/home";

# Move the current directory to /home
chdir( $dir ) or die "Cannot change directory to $dir, $!";
print "You are now in the directory $dir\n";

Executing the above program will output:

You are now in the directory /home
❮ Perl Redo Statement Perl Socket Programming ❯