[Israel.pm] why did it happen

Adriano Ferreira a.r.ferreira at gmail.com
Wed Jun 20 10:15:29 PDT 2007


On 6/20/07, Yossi Itzkovich <Yossi.Itzkovich at ecitele.com> wrote:
> Hi,
>
> A college here wanted to write this code:
> my $a=(27>20)?"big":"small";
>
> And instead wrote:
> my $a= (27>20)?$a="big":$a="small");

Hey, that took me a while to decipher. The answer is that the above
expression parses to:

      my $a = (   (27>20) ? ( $a="big" ) : $a       ) = "small";

and then, since (27>20) is true

      my $a = ( $a = "big" ) = "small" ;

which even though assigns "big" to $a is overrided by "small" in the
next instant.

That's what B::Deparse says: see

$ perl -MO=Deparse  -e '(27>20)?$a="big":$a="small";print $a'
($a = 'big') = 'small';
print $a;
-e syntax OK

or

$ perl -MO=Deparse  -e '($x,$y)=(27,20); my $a=
($x>$y)?$a="big":$a="small";print $a'
($x, $y) = (27, 20);
my $a = $x > $y ? ($a = 'big') : $a = 'small';
print $a;
-e syntax OK

What you want should be written

$ perl -MO=Deparse  -e '($x,$y)=(27,20); my $a=
($x>$y)?($a="big"):($a="small");print $a'
($x, $y) = (27, 20);
my $a = $x > $y ? ($a = 'big') : ($a = 'small');
print $a;
-e syntax OK

with explicit parentheses.

>
> Surprisingly $a was set to "small".  Why ?
>
> Yossi
>
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl
>



More information about the Perl mailing list