http://www.perlmonks.org?node_id=906218


in reply to Re: How to process multiple input files?
in thread How to process multiple input files?

I worry that an empty file will stop it prematurely. Or a file might contain just "0" or somesuch, but that's less likely. Since he's slurping whole files rather than reading lines, I think it would be prudent to test for defined. (Hmm, what does the normal line-oriented read do if an empty file is in the list? Maybe it's always an issue.)

update: never mind. In production code I would have simply written defined to be sure, but looking through the docs I see that this construct is special even in the case of explicit assignment. I know that the quick while(<>) tests for defined, or started to at some specific version of Perl (I remember the classic Camel book explaining how lines are never False because they end in "\n"), but wasn't sure that applied when assignment was being made.

In general, I rely less on special cases and magical meanings in well-written production code than in a quick one-liner. Declaring variables, and not using $_ much falls into the same category, so I somehow was thinking the magic was not in effect.

Replies are listed 'Best First'.
Re^3: How to process multiple input files?
by jwkrahn (Abbot) on May 23, 2011 at 06:44 UTC
    I think it would be prudent to test for defined.

    The code I posted:

    while ( my $line = <> ) {

    does test for defined.

      No, it tests for normal Truth. An undef, an empty string, a "0" etc. will all test as False after being assigned to $line.
        Check your answers, its easy :)
        $ perl -le " while ( my $line = <> ) { 1 } print $. " 0 0 0 0 ^Z 4 $ perl -MO=Deparse -le " while ( my $line = <> ) { 1 } print $. " BEGIN { $/ = "\n"; $\ = "\n"; } while (defined(my $line = <ARGV>)) { do { '???' }; } print $.; -e syntax OK