in reply to Re: Doubt on defined-ness
in thread Doubt on defined-ness

Actually I was about to answer just that, but then I tested it - and it turned out I was wrong.

Consider this:

$ hexdump -C foo 00000000 61 0a 30 |a.0| 00000003 $ perl -wle 'print "read line" while (my $x = <>)' foo read line read line $

I have a file foo here with an 'a', a newline, and a '0' - no trailing newline.

I'd expect just one line of output, because 0 is false. But why am I getting two lines? That doesn't seem to be logical to me.

So I modified my test scrpt a bit:

$ perl -MDevel::Peek -wle 'while (my $x = <>){ print "read line"; pri +nt "and its true" if $x }' foo read line and its true read line

So, the second line evaluates to true in the while-condition, but not in the following if-condition. Is there some kind of special magic? If yes, where is it documented?

Update ok, got it. Thank you all. I didn't realize it works for arbitrary variable names, and thought that $_ was special cased.

Replies are listed 'Best First'.
Re^3: Doubt on defined-ness
by FunkyMonk (Bishop) on Jun 18, 2008 at 19:35 UTC
    It's because perl applies its magic to your while. Deparse shows it as
    while (defined(my $x = <ARGV>))


    Unless I state otherwise, all my code runs with strict and warnings
Re^3: Doubt on defined-ness
by betterworld (Curate) on Jun 18, 2008 at 19:38 UTC
    It's just syntactic sugar. Perlop says:
           The following lines are equivalent:
    
               while (defined($_ = <STDIN>)) { print; }
               while ($_ = <STDIN>) { print; }
               while (<STDIN>) { print; }
    
    
Re^3: Doubt on defined-ness
by tinita (Parson) on Jun 18, 2008 at 19:39 UTC
    So, the second line evaluates to true in the while-condition, but not in the following if-condition. Is there some kind of special magic? If yes, where is it documented?
    the only location where i found it mentioned after a quick search is in perlvar $_:
    $ARG $_ The default input and pattern-searching space. The following pairs are equivalent: while (<>) {...} # equivalent only in while! while (defined($_ = <>)) {...}
    edit: and in perlsyn
    edit: ah, it's in perlop, like betterworld mentioned. overlooked it.