tlm has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Idle search for a file-read idiom
by davido (Cardinal) on Apr 22, 2005 at 15:38 UTC | |
|
Re: Idle search for a file-read idiom
by revdiablo (Prior) on Apr 22, 2005 at 16:28 UTC | |
|
Re: Idle search for a file-read idiom
by starbolin (Hermit) on Apr 22, 2005 at 15:51 UTC | |
by starbolin (Hermit) on Apr 22, 2005 at 16:05 UTC | |
|
Re: Idle search for a file-read idiom
by 5mi11er (Deacon) on Apr 22, 2005 at 15:41 UTC | |
by polettix (Vicar) on Apr 22, 2005 at 16:26 UTC |