One idiom I sometimes use (in quick one-off scripts) for reading a file is `cat ...`, like this:
but it has the drawback that the entire file is read into a list before it is processed, which can be a problem for large files. It would be better to use a while loop that reads and processes one line at a time, but the best while idiom I've been able to come up with isfrobnicate( $_ ) for `cat foobar.txt`;
which is a bit long, and relies on the @ARGV hack. Is there something more succinct and/or less klugey?{ local @ARGV = 'foobar.txt'; frobnicate( $_ ) while <>; }
Update: From the responses I realize that I should have been clearer about noting that there are some special cases for which I already know fine idioms. For example, if the filename is given to the script via @ARGV, then it's hard to beat something as simple as
Similarly, if all the script does is process lines from one or more input files, thenfrobnicate( $_ ) while <>;
is plenty simple. The situation that I was referring to is the more general one in which the filename is obtained in some way other than via @ARGV, and the script does more than process lines read from input files (in which case -n less convenient). In fact, most of the scripts I work on are too long to be suitable for the command line.#!perl -n frobnicate( $_ );
the lowliest monk
In reply to Idle search for a file-read idiom by tlm
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |