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

Dear Monks,

I would like to check the last modified time of my file. So does the following code look okay:

my $hour = 1 / 24; while ( -M $myFile < $hour ) { sleep (10); } if ( -M $myFile > $hour ) { print "file has not been modified for more than 1 hr \n"; }

Replies are listed 'Best First'.
•Re: file modified
by merlyn (Sage) on Jan 07, 2005 at 16:06 UTC
    There are two reasons why your "if" condition might be false. I'm curious as to which one of these was more of your concern:
    • The file was modified precisely one hour ago
    • Someone else modifies the file between the while loop and the if test
    If neither of these are your concern, then I'd remove the entire if construct, leaving only the body statement (the print operation).

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      Merlyn, I'm surprised you didn't point out that the result of -M can be undef if the stat fails, and that should be checked for, even if $myFile is a filehandle.

Re: file modified
by ambrus (Abbot) on Jan 07, 2005 at 16:23 UTC

    For me, it doesn't look right. Note that -M subtracts $^T (the invocation time of perl) from the mtime, so if you don't change the file, the result of -M won't increase in such a loop.

      Yeah it does not work properly. Basically if a file has not been modified for more than an hour, I go and check the contents of the file (comparison etc.), else I wait till the last modified time becomes more than 1 hr

      What is really happening is that my code goes into the while loop and does not come out...even after an hour. What do you advice? Thanks.

        What is really happening is that my code goes into the while loop and does not come out...even after an hour. What do you advice? Thanks.
        (Smacking hand on forehead...)

        It would have helped for you to say that! OK, I see what's happening now. -M is not going to change in that loop for a file that's being "left alone", because the value is measured relative to the start of the program (as captured in $^T)!

        Maybe what you want is more like this:

        { die unless my @stat = stat $the_file; my $seconds_until_one_hour_old = 3600 - (time - $stat[9]); last if $seconds_until_one_hour_old <= 0; # already old enough sleep $seconds_until_one_hour_old; # not yet redo; # and test again }

        -- Randal L. Schwartz, Perl hacker
        Be sure to read my standard disclaimer if this is a reply.