Dear Shawn,
You can use more than one file test on the same file to create a complex
logical condition.
Suppose you only want to operate on files that are both readable and writable;
you check each attribute and combine them with and:
if (-r $file and -w $file) {
...
}
Each time you perform a file test, Perl asks the filesystem for all of the
information about the file (Perl’s actually doing a stat each time, which we
talk about in the next section). Although you already got that information when
you tested -r, Perl asks for the same information again so it can test -w. What
a waste! This can be a significant performance problem if you’re testing many
attributes on many files.
The virtual filehandle _ (just the underscore) uses the information from the
last file lookup that a file test operator performed. Perl only has to look up
the file information once now:
if (-r $file and -w _) {
...
}
You don’t have to use the file tests next to each other to use _. Here we have
them in separate if conditions:
if (-r $file) {
print "The file is readable!\n";
}
if (-w _) {
print "The file is writable!\n";
}
You have to watch out that you know what the last file lookup really was,
though. If you do something else between the file tests, such as call a
subroutine, the last file you looked up might be different.
Starting with Perl 5.10, you could “stack” your file test operators by lining
them all up before the filename:
use 5.010;
if (-r -w -x -o -d $file) {
print "My directory is readable, writable, and executable!\n";
}
best,
Shaji
-------------------------------------------------------------------------------
Your talent is God's gift to you. What you do with it is your gift back to God.
-------------------------------------------------------------------------------
On Monday, 17 March 2014 2:35 PM, shawn wilson <[email protected]> wrote:
>From Archive::Tar::File - what's '_' and where is it documented?
sub _filetype {
my $self = shift;
my $file = shift;
return unless defined $file;
return SYMLINK if (-l $file); # Symlink
return FILE if (-f _); # Plain file
return DIR if (-d _); # Directory
return FIFO if (-p _); # Named pipe
return SOCKET if (-S _); # Socket
return BLOCKDEV if (-b _); # Block special
return CHARDEV if (-c _); # Character special
### shouldn't happen, this is when making archives, not reading ###
return LONGLINK if ( $file eq LONGLINK_NAME );
return UNKNOWN; # Something else (like what?)
}
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/