[HoustonTx.pm] Perl/Unix contract in Houston

houston at mail.pm.org houston at mail.pm.org
Thu Aug 7 11:41:39 CDT 2003


> Ditto. And in the spirit of keeping the board from becoming job postings
only,
> here's a little thingie I recently ran across to slurp a file into a
scalar:
>
> my $file_contents=do {local(@ARGV,$/)=$filename; <>};

Here's my take on it:

>From perlop:

The null filehandle <> is special: it can be used to emulate the
    behavior of sed and awk. Input from <> comes either from standard input,
    or from each file listed on the command line. Here's how it works: the
    first time <> is evaluated, the @ARGV array is checked, and if it is
    empty, "$ARGV[0]" is set to "-", which when opened gives you standard
    input. The @ARGV array is then processed as a list of filenames. The
    loop

And, as we know, when 'do' is given a block, it returns the value of the
last operation of the block, so to step through it :

do {

    local(@ARGV,$/) = $filename;

--snip--
         the assignment is given only one right-hand value, so $/ gets set
to undef, and since $/ is the input record seperator, setting it to undef
tells it to slurp the whole file (there are no newlines) when using <>.
--snip--

    <>;

--snip--
    As we see, from above for @ARGV, since no file has been opened or
selected, it pulls the file from @ARGV, and since there's no IRS -- it reads
the whole contents of the file.
--snip--

    }

The result of '<>' (the last operation of 'do's block) is then stored in
$file_contents.

For golfing, alas, since they didn't include the command line, here's my go
with the full entry:

perl -ne 'local($/);$x.=<>;'

Would append the contents of every file given as an argument, thereafter, or
STDIN if no arguments given, into the scalar '$x'.

e.g.:

perl -ne 'local($/);$x.=<>;' foo.txt bar.txt baz.txt

Of course, with -n, you don't get much control -- but there wasn't any other
functionality specified =)

===================================
Discreet Packaging: www.dronecolony.com
C. Church
===================================





More information about the Houston mailing list