Reading the content of a directory is not much different from reading a file. It also requires a file handle (or, directory handle, in this case) and uses its specialized open and close functions, opendir()
and closedir( )
, respectively. To actually read the directory, readdir(DIRECTORY_HANDLE)
must be called. If readdir( )
is called in a scalar context, it returns one directory entry every time it is called. If it is called in a list context, it will return a a list of all entries.
$entry = readdir(DIRECTORY_HANDLE); # scalar context
@entries = readdir(DIRECTORY_HANDLE); # list context
readDirectory1.pl
#!/usr/bin/perl # program opens a directory, reads it, and prints # the content to STDOUT # first, create a variable that holds the path to the directory $dir = "./test"; # we assume directory is a subdirectory # of the current working directory # second, create a directory handle named 'DIR': # directory handles are created with the opendir() function; # the first parameter is the name of the handle, # the second is the path and name of the directory # the directory hande is evaluated in a lsit context and passes # all diretory entries into the array @contents # print files in directory opendir(DIR, $dir) || die ("Fatal error: $!"); @contents= readdir(DIR); closedir(DIR); print "\nFiles in directory \'$dir\':\n"; foreach $entry (@contents) { # check if entry is a directory with the # '-d' file test; # the directory handle only returns the items in the # directory; if the entry is to be tested, the path from # the current working directory of the script needs to # be prepended next if (-d "$dir/$entry"); print $entry . "\n"; }
The second script uses a file test to filter the directory content and only print text files.
readDirectory2.pl
#!/usr/bin/perl # program opens a directory, reads it, and prints # the content to STDOUT # first, create a variable that holds the path to the directory $dir = "./test"; # we assume directory is a subdirectory # of the current working directory # second, create a directory handle named 'DIR': # directory handles are created with the opendir() function; # the first parameter is the name of the handle, # the second is the path and name of the directory # the directory handle is here evaluated in a scalar context # and readdir() returns on directory entry at a time print "\nSubdirectories in directory \'$dir\':\n"; # print subdirectories opendir(DIR, $dir) || die ("Fatal error: $!"); while ($entry = readdir(DIR)) { # check if entry is a file with the # '-f' file test; # the directory handle only returns the items in the # directory; if the entry is to be tested, the path from # the current working directory of the script needs to # be prepended next if (-f "$dir/$entry"); print $entry . "\n";; }