vlad_tepesch has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks
Can anybody explan me why the following code prints '1'?
my $a = 1; my $b = 0; my $c = $a and $b; print $c;
did i have to use different literals for boolean algebra? but even then writing
my $a = (1==1); my $b = (1==0); my $c = $a and $b; print $c;
the result is 1. but (1==0) evaluates to an empty string

please give me some clue
Thanks

Replies are listed 'Best First'.
Re: strange boolean algebra behaviour
by moritz (Cardinal) on Apr 04, 2012 at 10:14 UTC

    The problem is that and has very loose precedence, looser than the assignment operator. So you need to write $a && $b or ($a and $b). See perlop for more details.

    In Perl 5, the false value is represented as an empty string that can numify to 0 without a warning. That's what you are seeing in your second attempt.

      aarrrgghh!!!
      I could smash my head on table.
      operator precedence is a thing that i should have remember.

      I was utterly convinced that '&&' and 'and' are synonyms. Thank you.

        I could smash my head on table.

        Don't do that, that could hurt.

        But if you do do it, make/post a video

      use strict; use warnings; my $a = 1; my $b = 0; my $c = $a and $b; print "c=$c\n";
      This gives me warning that "Useless use of private variable in void context at tmp16.pl line 6.". line 6 is "my $c = $a and $b;". I first tried -MO=Deparse.
      C:\temp>perl -MO=Deparse tmp16.pl Useless use of private variable in void context at tmp16.pl line 6. use warnings; use strict 'refs'; my $a = 1; my $b = 0; $b if my $c = $a; print "c=$c\n"; $a = 1; $b = 0; $c = $a && $b; print "c=$c\n"; tmp16.pl syntax OK
      So, Deparse maybe says $b of "$b if my $c = $a;" is the useless use of private variable.
      regards.

        -p

        $ perl -MO=Deparse -e " my $foo = $bar and $baz; " $baz if my $foo = $bar; -e syntax OK $ perl -MO=Deparse,-p -e " my $foo = $bar and $baz; " ((my $foo = $bar) and $baz); -e syntax OK