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:
Or, perhaps:
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:
It's much easier to check permissions on a file using file test operators than it is to mask the mode value from stat :
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. |