in reply to accessing file attibutes

$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;

Replies are listed 'Best First'.
Re^2: accessing file attibutes
by Anonymous Monk on Nov 15, 2006 at 20:44 UTC
    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;
        Hmmm could you give me an example? Im not sure what you are talking about? So I wont need to use File::Stat at all?

      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.