10.2. Reading Directories

This has bitten us more times than we care to admit:

readdir() returns the list of filenames in the directory, but they are not qualified by the directory itself.

Consider the following program:

use strict;
use File::stat;

my $dir = shift || '.';
opendir DIR, $dir or die "Error opening directory $dir: $!\n";
while (defined (my $file = readdir DIR))
   {
   print "File $file was last modified on "
         . localtime(stat($file)->mtime), "\n";
   }
closedir DIR;

It takes a directory as its argument, defaulting to the current directory. This program prints out the names and modification times of all the files in the current directory. ...

Get Perl Debugged now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.