in reply to Can you read a false value from a file?

Just like
while (<FH>)
is equivalent to
while (defined($_ = <FH>))

while (my $line = <FH>)
is equivalent to
while (defined(my $line = <FH>))

This can be demonstrated using the following program.

open(my $in, '<', 'file.dat') or die("Unable to open input file: $!\n"); while (my $line = <$in>) { if ($line) { print("true\n"); } else { print("true for 'while', but false for 'if'\n"); } }

outputs

true for 'while', but false for 'if'

when a file.dat contains the lone character zero (0).

By the way, overloading aside, only the following evaluate to false: numerical expressions evaluating to zero, the string '0', the empty string '' and the undefined value. 0.0 and 0E0 are the same as 0, but neither '0.0' nor '0E0' are the same as '0'.

Replies are listed 'Best First'.
Re^2: Can you read a false value from a file?
by grantm (Parson) on Feb 11, 2006 at 09:39 UTC

    Ah, so a string with a trailing newline will never be false, but it's possible that the last line of the file won't have the trailing newline. So, without the defined( ... ) I might fail to process the last line But even then, my $line = <FH> will still return true.

      When you write while ($scalar = <FILEHANDLE>) { ... }, perl takes care of the test for definedness for you:
      $ perl -MO=Deparse -e 'open $fh,"foo.txt"; while (my $line = <$fh>) { +print $line }' open $fh, 'foo.txt'; while (defined(my $line = <$fh>)) { print $line; } -e syntax OK
      Did you only read the last line of my post? I said the opposite, and included a code sample proving the opposite. Even without the newline, it won't fail.

        No, I misread the whole thing - sorry.

        Is it documented anywhere that

        while (my $line = <FH>)

        is equivalent to

        while (defined(my $line = <FH>))