Directory handles


For a platform independent approach use opendir and readdir.

In order to read the content of a directory (that is the list of the files) first we have to open the directory similarly to the way we opened a file but using the opendir function This way we get a directory handle which we can use in subsequent operations.

Once the directory was opened successfully we can use the function readdir in a loop to get the names of the files in that directory


examples/shell/list_directory.pl
#!/usr/bin/perl
use strict;
use warnings;

my $dir = shift or die "Usage: $0 DIRECTORY\n";

opendir my $dh, $dir or die "Cannot open $dir: $!\n";
while (my $entry = readdir $dh) {
    if ($entry eq "." or $entry eq "..") {
        next;
    }
    print "$entry\n";
}
closedir $dh;

in LIST context readdir returns all the files in the directory.


opendir(my $dh, "/etc") or die $!;
@files = readdir $dh;