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

Hi,

stat does not work despite it is correctly installed (at least it is what cpan says)...



#!/usr/bin/perl -w

use File::stat;

$filename="path/file";

($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($filename) or die "Can't stat file $filename\n";

print "$filename at $mtime\n";
print "$filename at (stat($filename))[9]\n\n";

1;

Output:

path/file at
path/file at (stat(path/file))[9]

Any idea?

Thanks!

Replies are listed 'Best First'.
Re: stat($filename) fails ?!
by JadeNB (Chaplain) on Aug 07, 2009 at 06:06 UTC
    It seems from your code that you don't want to use File::stat. That module replaces your stat function with one that returns File::Stat objects that can be queried by name (like stat($filename)->mtime), rather than returning lists. Your first few lines of code will probably work if you remove use File::stat.

    Note that

    print "$filename at (stat($filename))[9]\n\n";
    has no chance of behaving the way you expect, because Perl has no way of knowing that that stat is supposed to be a function call—it's treated like any other text. (To put it more succinctly, function calls aren't interpolated.) You can write
    print "$filename at (", ( stat($filename) )[9], "\n\n";
    or use the old trick of array de-referencing:
    print "$filename at (@{[ ( stat($filename) )[9] ]})\n\n";

    UPDATE: If you do want to use File::stat, then you should replace

    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$bl +ksize,$blocks) = stat($filename) or die "Can't stat file $filename\n" +;
    by
    my $stat = stat($filename) or die "Can't stat file $filename";
    (no need for that newline), and then, rather than trying to access an array that isn't there, use a method call:
    print "$filename at (", $stat->mtime, ")\n";

Re: stat($filename) fails ?!
by XooR (Beadle) on Aug 07, 2009 at 06:13 UTC

    You doesn't use File::stat module properly. Calling stat($filename) returns reference to the stat object. So this is the way you should use it:

    #!/usr/bin/env perl use strict; use warnings; use File::stat; my $filename = $ARGV[0]; my $stat_obj = stat($filename) or die "Can't stat $filename"; print "$filename at " . $stat_obj->mtime() . "\n";
Re: stat($filename) fails ?!
by bichonfrise74 (Vicar) on Aug 07, 2009 at 06:12 UTC
    See what I have done. This works for me. Also, I didn't have to declare File::stat, why do you need to declare it?

    Maybe your file is not properly defined?
    #!/usr/bin/perl use strict; my $filename = q{c:\test.txt}; my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev, $size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($filename) or die "Can't stat file $filename\n"; print "$filename at $mtime\n"; print "$filename at " . (stat($filename))[9] . "\n\n";