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

I can't seem to get stat() to work. I have the PERL BLACK BOOK and think I am following it to a "T" but I can't get anything to work. So, I am at your mercy Here is what I think is the relevant part of my script.....

my @files; opendir (FILE,"/var/www/html/file") || die $!; @files = grep {-f "/var/www/html/file/$_"} readdir (FILE); closedir (FILE) || die $!; foreach $files (sort(@files)) { $mtime = stat($files); print $mtime; };
All it does is print the number 1. Am I using this wrong or don't have some permissions set right or something?. I'm just trying to add a date the file was last modified. Thanks for any help

Edited 2002-01-10 by Ovid

Replies are listed 'Best First'.
Re: A little help w/ stat() por favor...
by blakem (Monsignor) on Jan 11, 2002 at 06:34 UTC
    Since stat returns a list, you need to pick which element of that list interests you... Examining the stat man page shows mtime at index number 9. So, you might try:

    $mtime = stat($files)[9];

    $mtime = (stat($files))[9];
    Or, if you'd like a relative "time since" in fractional days, you could use:
    $days_since_modified = -M $files;
    Update: /me ducks to avoid the flying trout and fixes the syntax error

    -Blake

      Thanks for the fast reply. When I tried

      $mtime = stat($files)[9];

      I got syntax errors and it wouldn't work.

      $mtime = -M $files;

      printed out 1's next to each file.

      Any other suggestions?
        Oops, sorry... that should have been:
        $mtime = (stat($files))[9];

        -Blake

      This is in response to the correction. I am still just getting the number 1 with any of the 13 elements that I try
Re (tilly) 1: A little help w/ stat() por favor...
by tilly (Archbishop) on Jan 11, 2002 at 07:21 UTC
    As the usual rant goes, you are not using strict.pm, your error checks on open should include an explanation of the error, the filename and $! (you only include $!), and you should have a consistent indentation style.

    While none relate to your specific question, all of them will wind up helping you again and again.

Re: A little help w/ stat() por favor...
by clintp (Curate) on Jan 11, 2002 at 07:11 UTC
    Maybe I missed this in the suggestions: but the files coming back from readdir don't have the full pathname, and you're storing them that way (just the filenames). When you -f them, you're remembering to append the pathname on them, but when you stat the files later...you forgot to prepend "/var/www/..." again. (In addition to the other problem of not using stat()'s return value correctly.)
Re: A little help w/ stat() por favor...
by nikos (Scribe) on Jan 14, 2002 at 03:17 UTC
    You should get the 10th element of the list returned by "stat".
    $mtime=(stat($files))[9];
    I consider 1 to be returned just as a "flag" that there is an answer. ;) A very stupid explanation from me btw, sorry