On Fri, Nov 6, 2009 at 6:48 PM, John W. Krahn <jwkr...@shaw.ca> wrote:

> tom smith wrote:
>
>> On Mon, Nov 2, 2009 at 5:10 AM, John W. Krahn <jwkr...@shaw.ca> wrote:
>>
>>  Philip Potter wrote:
>>>
>>>  2009/11/2 Thomas Bätzler <t.baetz...@bringe.com>:
>>>>
>>>>  while( my $line = <$file> ){
>>>>> <snip>
>>>>> }
>>>>>
>>>>>  Won't this loop terminate early if there is a blank line or a line
>>>> containing only '0'? If I do a readline loop I always do:
>>>> while (defined ($line = <$file>))
>>>>
>>>> Is there something magical happening here I don't know about? I know
>>>> about the magical:
>>>>
>>>> while (<$file>)
>>>>
>>>> which is equivalent to:
>>>>
>>>> while (defined($_ = <$file>))
>>>>
>>>> but I don't know of any magic in the while loop at the top.
>>>>
>>>>  Whether you use:
>>>
>>> while ( <FH> )
>>>
>>> Or:
>>>
>>> while ( my $line = <FH> )
>>>
>>> The condition is always tested for undefinedness.
>>>
>>
>> Is that correct?
>>
>
> Yes, that is correct.
>
>
>
>  Or is the condition in the while always tested for *truth*?
>>
>
> When readline() is not involved, yes.
>
>
>
>  I read that in perl the following evaluate to false:
>>
>> 0
>> '0'
>> undef
>> ''  # Empty scalar
>> ()  # Empty list
>> ('')
>>
>>
>> The way I see it, a blank line in a file is "\n" (not ""); and a line with
>> only a zero on it is "0\n" (not "0").   Both of those strings evaluate to
>> true in the while condition.  When the "line input operator" hits
>> end-of-file, it returns the value undef.  Because undef evaluates to
>> false,
>> the while loop ends.  I don't think there is any magic going on there, is
>> there?
>>
>
> $ perl -e'
> my $file = q/TEST/;
> open FH, ">", $file or die "open: $file $!";
> print FH "one\ntwo\nthree\n0";
> close FH;
>
> open FH, "<", $file or die "open: $file $!";
> while ( <FH> ) { print "-->$_<--"}
> close FH;
>
> unlink $file or die "unlink: $file $!";
> '
> one
> two
> three
> 0
>
>
> Note that the last line is "0" not "0\n" and it is still printed out.
>
>
Thanks.  I also read the section on "I/O Operators" in perlop, which
explains that the test is a "defined" test rather than a "truth" test.

Reply via email to