Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

stat : error handling

by gepebril69 (Scribe)
on Jan 03, 2013 at 13:24 UTC ( #1011449=perlquestion: print w/replies, xml ) Need Help??
gepebril69 has asked for the wisdom of the Perl Monks concerning the following question:

I want to use the function stat to determine the last modified date of a file. This can be done by

$FileTimeLastMod = (stat ($FileName))[9];

But how to detect if something in this function call fails? There is a brief description on the manual page of Perl, but I can't figure out what they mean. English is not my native tongue:

Returns a 13-element list giving the status info for a file, either the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is omitted, it stats $_ (not _ !). Returns the empty list if stat fails.

What is the code I have to use? Thanks in advance

Replies are listed 'Best First'.
Re: stat : error handling
by toolic (Bishop) on Jan 03, 2013 at 13:38 UTC
    Try something like this:
    use warnings; use strict; my @stats = stat 'foo'; if (@stats) { print "OK\n"; } else { print "Error\n"; }

    Also, use <blockquote> instead of quote.

      Thanks Toolic

      Have updated the quote to quoteblockquote And your code works! Excellent. I get it.

      Do you have any idea why perlmonks uses a textstyle website with 90's looks? I mean we don't need eyecandy, but maybe some styling would be nicer and more functional.

Re: stat : error handling
by johngg (Abbot) on Jan 03, 2013 at 14:03 UTC

    The o/s error is recorded in $!.

    $ perl -E ' > @stats = stat q{notThere} or die $!;' No such file or directory at -e line 2. $



      Thx Johngg

      I stick to the non-die solutions. They are not real handy in 24/7 operational systems.... ;)

        Well, you don’t need to use die to get information from $!:

        #! perl use Modern::Perl; for my $file ('', 'Non-Existent.txt') { if (my @stats = stat $file) { say "File '$file' last modified: ", $stats[9]; } else { say "stat failed for file '$file': $!"; } }

        Output (on my machine):

        0:17 >perl File '' last modified: 1357188675 stat failed for file 'Non-Existent.txt': No such file or directory 0:17 >

        Hope that helps,

        Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

        The solution was $! and, as Athanasius points out, die had nothing to do with it other than to illustrate that the variable is available ;-)



Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1011449]
Approved by marto
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2017-09-23 22:01 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (273 votes). Check out past polls.