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

Im trying to get the date that a file was last modified. Im using File::Stat to get but for some reason I can read the directory but cant access it. Any help would be appreciated from a Perl noob. Code is below...
#!/usr/bin/perl use File::stat; opendir(DIR, '/cdw/dept/dss/home_dir/s006258/') || die "Unable to open directory '/cdw/dept/dss/home_dir/s006258/': + $!"; while ($file =~ <DIR>) { ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($file); print"$file , $mtime\n"; } closedir DIR;

Replies are listed 'Best First'.
Re: accessing file attibutes
by ikegami (Patriarch) on Nov 15, 2006 at 20:07 UTC

    $file =~ <DIR>??? Try defined($file = readdir(DIR))

    Update: Furthermore, don't forget that readdir only returns a file name, not a complete path.

    #!/usr/bin/perl use strict; use warnings use File::Spec qw( ); my $dir = '/cdw/dept/dss/home_dir/s006258'; opendir($dh, $dir) or die "Unable to open directory '$dir': $!\n": while (defined(my $file = readdir($dh))) { my $path = File::Spec->catfile($dir, $file); my $mtime = (stat($path))[9]; printf("%s was last modified on %s\n", $file, scalar(localtime($mtime)), ); } closedir $dh;
      Hey works great, I made a few modifications... Now how would I compare it to a date (say if itsa file that hasnt been modified in 2 days then I need to delete). I just need to know how to compare the date. Im not even sure what type of format $mtime is.. Heres what I changed it to using your code:
      $dir = "/cdw/dept/dss/home_dir/s006258"; die("Unable to open directory '$dir': $!") unless(opendir($dh, $dir)); while (defined(my $file = readdir($dh))) { $path = $dir."/".$file; if(-d $path) { $mtime = (stat($path))[9]; print "$path ,".scalar(localtime($mtime))."\n"; } } closedir $dh;

        I made a few modifications

        That's unforunate.

        • $path = $dir."/".$file; doesn't really save you anything over catfile and it's less portable.

        • Reguarding xxx if yyy, most people avoid hiding the intent of the statement in yyy like you did.

        • I noticed you removed "\n" from the error message. If your error message relies on the line number to be readable, it isn't. It's particularly bad to display the line number in this case because the error is a user input error.

        • You unbound the scope of $dh, $mtime and $path by removing my. That's just plain wrong.

        Four steps backward.

        Now how would I compare it to a date

        Two approaches:

        • Use if (-M $path < 2) to check if it's too old. Documented in -X.

        • Do my $time_limit = time() - 24*60*60; outside the loop, and use if ($mtime < $time_limit) to check if it's too old.

Re: accessing file attibutes
by Joost (Canon) on Nov 15, 2006 at 20:11 UTC