Item 56: Don t forget the file test operators.


Item 56: Don't forget the file test operators.

One of the more frequently heard questions from newly minted Perl programmers is, "How do I find the size of a file?" If this question is asked on the Perl newsgroup comp.lang.perl.misc , almost invariably there will be be one response like the following:

 ($dev,$ino,$mode,$nlink,$uid,    $gid,$rdev,$size,$atime,$mtime,    $ctime,$blksize,$blocks) =      stat($filename); 

Poster must have been reading the stat man page.

Or, perhaps:

 ($size) = (stat $filename)[7]; 

Poster read man page and "optimized" it.

But the short answer is:

 $size = -s $filename; 

I'm not sure why, but many people overlook Perl's file test operators. This is a shame, because they are succinct and efficient, and tend to be more readable than equivalent constructs written using the stat operator.

File tests fit into loops and conditions very well. Here, for example, is a list of the text files in a directory:

 @textfiles =    grep { -T } glob "$dir_name/*"; 

Tests use $_ by default.

It's much easier to check permissions on a file using file test operators than it is to mask the mode value from stat :

 print "$f is: ";  print "writeable " if -w $f;  print "readable " if -r _;  print "executable " if -x _; 

Special pseudo-filehandle _ refers to the result of the last stat or lstat .

This example uses the special pseudo-filehandle _ , which the file test operators can use to refer to the result of the last stat performed, whether by an explicit call or as the result of a recent use of a file test operator. Because stat is slow ( generally requiring a disk access), this is a worthwhile optimization.



Effective Perl Programming. Writing Better Programs with Perl
Effective Perl Programming: Writing Better Programs with Perl
ISBN: 0201419750
EAN: 2147483647
Year: 1996
Pages: 116

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net