Perl Tutorial on Perl Directories

following are the standard functions used to play with directories.

opendir dirhandle, expr  # to open a directory
readdir dirhandle        # to read a directory
rewinddir dirhandle      # positioning pointer to the begining
telldir dirhandle        # returns current position of the dir
seekdir dirhandle, pos   # pointing pointer to pos inside dir
closedir dirhandle       # closing a directory.

display all the files

there are various ways to list down all the files available in a particular directory. first let's use the simple way to get and list down all the files using the glob operator −

#!/usr/bin/perl

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

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

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

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

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

# display all the files from /tmp and /home directories.
$dir = "/tmp/* /home/*";
@files = glob( $dir );

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

here is another example, which opens a directory and list out all the files available inside this directory.

#!/usr/bin/perl

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

one more example to print the list of c source files you might use is −

#!/usr/bin/perl

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

create new directory

you can use mkdir function to create a new directory. you will need to have the required permission to create a directory.

#!/usr/bin/perl

$dir = "/tmp/perl";

# this creates perl directory in /tmp directory.
mkdir( $dir ) or die "couldn't create $dir directory, $!";
print "directory created successfully\n";

remove a directory

you can use rmdir function to remove a directory. you will need to have the required permission to remove a directory. additionally this directory should be empty before you try to remove it.

#!/usr/bin/perl

$dir = "/tmp/perl";

# this removes perl directory from /tmp directory.
rmdir( $dir ) or die "couldn't remove $dir directory, $!";
print "directory removed successfully\n";

change a directory

you can use chdir function to change a directory and go to a new location. you will need to have the required permission to change a directory and go inside the new directory.

#!/usr/bin/perl

$dir = "/home";

# this changes perl directory  and moves you inside /home directory.
chdir( $dir ) or die "couldn't go inside $dir directory, $!";
print "your new location is $dir\n";