hipnoodle has asked for the wisdom of the Perl Monks concerning the following question:

Can anyone tell me why this use of stat only gives me the age of . and .. and not all files. I do get all file names, but only get $mtime for . and .. Muchos thankyous in advance.
opendir(DIR, $dirname) or die "can't opendir $dirname: $!"; while (defined($file = readdir(DIR))) { $mtime= (stat($file))[9]; print "$file : $mtime<br>"; } closedir(DIR);

Replies are listed 'Best First'.
Re: stat only gives info on . & ..
by ikegami (Patriarch) on Jan 18, 2007 at 18:45 UTC

    $file contains just the file name, not the path to the file. Fix:

    use File::Spec::Functions qw( catfile ); opendir(my $dh, $dirname) or die "can't opendir $dirname: $!\n"; while (defined(my $filename = readdir($dh))) { my $fq_filename = catfile($dirname, $filename); my $mtime = (stat($fq_filename))[9]; print "$filename: $mtime<br>"; } closedir($dh);

    I also made the following changes:

    • I made the variable names more consistant ($filename is similar to $dirname).
    • I converted the variables into lexicals. (How come you're not using use strict;?!)
    • I converted the handles into lexicals.
    • I removed the line number from the error message. You shouldn't need the line number in error messages about IO failures. You have a poor message if you do.

    I didn't fix the bug where you print out plain text when HTML text is expected.

      Hey, thanks I really appeciate the help. I was assuming stat would know to work on the current directory. This will go into an html doc so that's why you see the break tag. Cheers

        I was assuming stat would know to work on the current directory.

        stat does work on the current directory. Unfortunately, the files you are listing aren't in the current directory. They are in dir $dirname. . and .. happens to exist in both the current directory and in dir $dirname, so that's why stat "worked" on them. (Well, it didn't really work, since you weren't getting info on what you thought you were getting info.)

        This will go into an html doc so that's why you see the break tag. Cheers

        The bug I pointed out isn't the tags, it's the plain text being printed along with the tags. That plain text needs to be converted to HTML (using CGI's escapeHTML or HTML::Entities's encode_entities).

        The latest thing in web-niceness is to use <br /> for XHTML compliance.

        Never mind, I guess I was thinking everybody was supposed to use XHTML now. People yelled at me loudly last time I typed <br>. Guess I misunderstood why.

        Update: strike that please!

        non-Perl: Andy Ford