in reply to 'and next' question

When do think $hash{$_}++ will return a true value for the logical 'and' to evaluate the other side?

Replies are listed 'Best First'.
Re: Re: 'and next' question
by pg (Canon) on Oct 26, 2003 at 20:09 UTC

    Here is the explanation:

    Play with the code by changing and to or:

    my %hash; while ( <DATA> ) { chomp; $hash{$_}++ or next if $_ > 5; print; } __DATA__ 3 7 9 1
    The reason is that $hash{$_} ++ resolves to zero (if there is no ++, it resolves to undef), when the first time you encounter that particular key. As he is using the value of $hash{$_} before ++, and $hash{$_} is 0 (not for the second time and afterwards), so the part before and resolves to false. He used and, so the entire condition fails right the way, and there is no point for Perl to evaluate the "next if" part.

    But this particular logic would fail if he has duplicate keys.

    The following would print four 7's for him (not five 7's):

    my %hash; while ( <DATA> ) { chomp; $hash{$_}++ or next if $_ > 5; print; } __DATA__ 3 7 9 1 7 7 7 7