Stack file test operators in Perl 5.10 or later.Use the _ virtual filehandle to reuse data from the last stat.Don't call stat directly when a file test operator will do.The -T file test decides if the contents are text by sampling part of the file and guessing.Īlmost all file tests use $_ by default: my = grep glob '*' Things to remember Here, for example, is a list of the text files in a directory. If you want to read about them, you tell perldoc to give you the function named -X: % perldoc -f -Xįile tests fit into loops and conditions very well. Curiously, the file test operators are the first functions listed in perlfunc, because they are under the literal -X. This is a shame they are succinct and efficient, and tend to be more readable than equivalent constructs written using the stat operator. Maybe they are old C programmers, maybe they've seen only the programs that other people write, or they just don't trust them. Many people overlook Perl's file test operators. And indeed, it is if you use the -s file test operator, which tells you the file size in bytes: my $size = -s $filename Perl is specifically designed to make the common things easy, so this should be really easy. When you are working this hard to get something that should be common, stop to think for a moment. Or, perhaps they know how to avoid the extra variables that they don't want, so they use a slice (Item 9): my ($size) = ( stat $filename ) One of the more frequently heard questions from newly minted Perl programmers is, "How do I find the size of a file?" Invariably, another newly minted Perler will give a wordy answer that works, but requires quite a bit of typing: my ( You can also store filehandles in scalar variables, and select which one you want to use later. You can use the filehandle interface to do most of the heavy lifting for you. However, Perl can apply its file-handle interface to almost anything. You probably think of files as things on your disk with nice icons. Perl's strength goes beyond mere files, though. Its heritage includes some of the most powerful utilities for processing data, so it has the tools it needs to examine the files that contain those data and to easily read the data and write them again. Effective Perl Programming: Ways to Write Better, More Idiomatic Perl, 2nd Edition
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |