One idiom I sometimes use (in quick one-off scripts) for reading a file is `cat ...`, like this:

frobnicate( $_ ) for `cat foobar.txt`;
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 is
{ local @ARGV = 'foobar.txt'; frobnicate( $_ ) while <>; }
which is a bit long, and relies on the @ARGV hack. Is there something more succinct and/or less klugey?

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

frobnicate( $_ ) while <>;
Similarly, if all the script does is process lines from one or more input files, then
#!perl -n frobnicate( $_ );
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.

the lowliest monk


In reply to Idle search for a file-read idiom by tlm

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.