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

Hi,

I'm really doing something obviuously wrong. I'd like to go through files in directory sorted by date and print agte in days and hours for each of them.

I have:
open FILES1, "ls *|" or die "Can not run ls $!\n"; while (<FILES1>) { my $time1=time(); my $mtime = (stat ($_))[9] or die "Stat problem on $_: $!\n"; my $age_hours=($time1 - $mtime) / 3600 ; my $age_days= $age_hours/24; print "Got time $mtime hours: $age_hours days: $age_days \n"; } close FILES1;


I get error of no such file on stat call...
What is wrong ?

Thanks,

Robert.

Replies are listed 'Best First'.
Re: Strange problem with stat
by valdez (Monsignor) on Feb 14, 2004 at 14:52 UTC

    You forgot to chomp($_): there is a new-line at the end of every filename.

    Ciao, Valerio

Re: Strange problem with stat
by VSarkiss (Monsignor) on Feb 14, 2004 at 17:20 UTC

    Don't even bother with ls. As you've found, that has its own tricky stuff, and isn't portable. Just use Perl built-ins, such as something like this: (note, untested)

    opendir D, '.' or die "Can't opendir .: $!\n"; while (readdir D) { # The body of your loop stays the same. } closedir D;
    HTH

Re: Strange problem with stat
by ctilmes (Vicar) on Feb 14, 2004 at 17:40 UTC
    Other comments are right and will work too. I like using glob for this sort of thing:
    foreach (glob('*')) { ... }
Re: Strange problem with stat
by tachyon (Chancellor) on Feb 14, 2004 at 20:13 UTC
    [root@devel3 tmp]# perl -e 'printf"%-20s%.3f days\n",$_,-M $_ for map{ +s/\s+$//;$_} `ls -t`'; session 0.096 days replicate.log 0.778 days bayes 1.239 days genpred 1.868 days 079_pred 1.973 days unmerged 2.045 days nMerge 2.045 days anticat 2.052 days hashMerge 2.126 days 079_cat 2.172 days 000_cat 2.172 days mysql.sock 3.149 days [root@devel3 tmp]#

    cheers

    tachyon

Re: Strange problem with stat
by CountZero (Bishop) on Feb 14, 2004 at 16:37 UTC
    If you want it to work on Windows use open FILES1, "dir /B |" and don't forget to chomp !

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Strange problem with stat
by pelagic (Priest) on Feb 14, 2004 at 15:54 UTC
    you just ask for the file. You should check directory/file instead.