My Favorite Modules: File::stat
File::stat
overrides the core stat()
and lstat()
functions. Instead of arrays, the new functions return an object having methods corresponding to the elements of the arrays returned by the original functions. This module has been in core since Perl 5.004.
The advantage of this module is clearer code. For example, to get the size of file $file
without it is something like
my $size = ( stat $file )[7];
But with this module the same effect is given by
my $size = stat( $file )->size();
Once you have the object in hand, you cam query it for any of its properties, so if you want both size and modification time, instead of
my ( $size, $mtime ) = ( stat $file )[ 7, 9 ];
you can say
my $st = stat $file; my $size = $st->size(); my $mtime = $st->mtime();
Starting with File::stat
version 1.02 (which ships with Perl 5.12) the returned object overloads the file test operators (-X
), so that the above example could be extended by something like
my $mine = -o $st;
This will not work for -t
, -T
, and -B
because these can not be determined from the results of a core stat()
call.
In addition, File::stat
versions 1.02 and above support a cando()
method as an alternate implementation to the file access tests -r
, -w
, -x
, -R
, -W
, and -X
. This method takes two arguments. The first is one of the Fcntl
constants S_IRUSR
, S_IWUSR
, or S_IXUSR
, and the second is a Boolean which selects the effective UID (if true) or the real UID (if false).
Unfortunately, There Ain't No Such Thing As A Free Lunch. There are a few things to be aware of if you use this module:
- The
stat()
andlstat
functions provided by this module no longer make implicit use of the topic variable$_
. Fortunately, calls of these without arguments become syntax errors, and you can always supply$_
as an explicit argument. - The
stat()
andlstat
functions provided by this module no longer interact with special file handle_
. Fortunately, calls of (e.g.)stat _
are an error ifuse strict 'subs';
is in effect. Note that you can still use explicit file handles. - This module's overrides of the file access operators ignore the
filetest
pragma -- with a warning ifuse filetest 'access';
is in effect. You can, of course, still get this functionality, but you will have to test the original file name.
And of course, you can always access the overridden functions if you need to by calling CORE::stat()
or CORE::lstat()
.
Previous entries in this series:
Leave a comment