What is the semantics of "stat" on dirhandle in Perl?
While researching another question, I noticed that a stat
Perl function can take a dirhandle as its argument (instead of a file or filename).
However, I cannot find examples of how to use this correctly - there are none in the Perl manual.
Can anyone show an example on how to use it?
source to share
You use it the same way you would for a file or file descriptor:
#!/usr/bin/perl
use strict;
my $dir = shift;
opendir(DIR, $dir) or die "Failed to open $dir: $!\n";
my @stats = stat DIR;
closedir(DIR);
my $atime = scalar localtime $stats[8];
print "Last access time on $dir: $atime\n";
The ability to use stat for directory descriptors was only added in Perl 5.10, so it should be avoided if you care about portability.
source to share
You use it in the same way as stat
in the file descriptor:
<~> $ mkdir -v foo ; perl -e 'opendir($dh , "./foo"); @s = stat $dh; print "@s"'
mkdir: created directory `foo'
2049 11681802 16877 2 1001 1001 0 4096 1228059876 1228059876 1228059876 4096 8
(Personally, I like to use File::stat
to get nice named accessories, so I don't have to remember (or look for) that the fifth item is a UID ...)
source to share
Just remember that if a handle has ever been used as a file handle, as well as a dirhandle, stat will apply to the file, not the directory:
$ perl -wl
opendir $h, "." or die;
open $h, "/etc/services" or die;
print "dir:".readdir($h);
print "file:".readline($h);
print stat("/etc/services");
print stat(".");
print stat($h);
close($h);
print stat($h);
__END__
dir:.
file:# Network services, Internet style
205527886633188100018274122800783211967194861209994037409640
20551515522168777410001000020480122803711512280371021228037102409640
205527886633188100018274122800783211967194861209994037409640
stat() on closed filehandle $h at - line 1.
(Are you trying to call stat() on dirhandle $h?)
source to share
I am using Perl 5.10.1 on windows (ActivePerl) and stat on dirhandle is not working. But doing stat on the directory path line works.
work
my $mtime = (stat( $directory ))[ 9 ];
print "D $directory $mtime\n";
it is not ("dirfd function not implemented ...")
my $dh;
if( opendir( $dh, $directory ) == 0 ) {
print "ERROR: can't open directory '$directory': $!\n";
return;
}
$mtime = (stat( $dh ))[ 9 ];
print "D $directory $mtime\n";