13.7. Using the Perl stat( ) Call's Cached Results
When you call stat( ) (or its variants -M, -e, etc.), the returned information is cached internally. If you need to make an additional check on the same file, assuming that it hasn't been modified, use the _ magic file handle and save the overhead an unnecessary stat( ) call. For example, when testing for existence and read permissions, you might use:
my $filename = "./test"; # three stat( ) calls print "OK\n" if -e $filename and -r $filename; my $mod_time = (-M $filename) * 24 * 60 * 60; print "$filename was modified $mod_time seconds before startup\n";
or the more efficient:
my $filename = "./test"; # one stat( ) call print "OK\n" if -e $filename and -r _; my $mod_time = (-M _) * 24 * 60 * 60; print "$filename was modified $mod_time seconds before startup\n";
Two stat( ) calls were saved!
If you need to stat( ) the mod_perl script that is being executed (or, in a handler, the requested filename in $r->filename), you can save this stat( )system call by passing it $r->finfo as an argument. For example, to retrieve the user ID of the script's owner, use:
my $uid = (stat $r->finfo);
During the default translation phase, Apache calls stat( ) on the script's filename, so later on we can reuse the cached stat( )structure, assuming that it hasn't changed since the stat( ) call. Notice that in the example we do call stat( ), but this doesn't invoke the system call, since Perl resuses the cached data structure.
Furthermore, the call to $r->finfostores its result in _ once again, so if we need more information we can do:
print $r->filename, " is writable" if -e $r->finfo and -w _;
Copyright © 2003 O'Reilly & Associates. All rights reserved.