in reply to Evaluating the condition ($x)

Btw I can confirm that I get the same result on Windows XP TinyPerl 5.8.

My suspicion is that the answer may lie in the precedence of operators. The = seems to be evaluated first, and then the the ?: group second. Am I right?

We could confirm this by doing : $z = 1; $x = 1; $z = $x ? $z = 2 : $z *= 9; print $z;

Now, the output is not 1, it's not 9 but 18. How does it become 18? The fact that it's 18 seems to suggest that first the $z = 2 gets evaluated, and then immediately after that the $z *= 9 gets evaluated. (Note: the = sign and *= are on the same level of precedence.)

Edit: Another interesting code is $z = 1; print $z *= 2, $z *= 9; # This prints 1818 instead of 218

Edit: I thought I was onto something, but apparently not. I'm just even more lost now. I did this :

my $A = 1; my $B = 7; my $C = 5; my $D = 0; $D = $A ? $B *= 2 : $C *= 9; print "A=$A B=$B C=$C D=$D";

And the output is..... :drum roll:

A=1 B=126 C=5 D=126

Okay. I give up. I'm lost! Maybe we discovered a bug? How does $B become 126? Lol

Replies are listed 'Best First'.
Re^2: Evaluating the condition ($x ||= $y)
by syphilis (Archbishop) on Aug 26, 2024 at 03:46 UTC
    Am I right?

    Yes, I think so.
    The problem is fixed by changing the troublesome rendition to:
    ($x) ? ($z = "true\n") : ($z = "false\n"); print $z;
    I sure am glad I generally go for the extra bit of typing and use if/else. Bloody hell ... the amount of time I can spend in a ternary op rabbit hole ... :-(
    Thanks harangzsolt33, Fletch, hv.

    Cheers,
    Rob
      #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11161348 use warnings; my $x = '1'; my $z = "undetermined\n"; ($x) ? print "true\n" : print "false\n"; ($x) ? $z = "true\n" : $z = "false\n"; print $z; # fewer parens :) $x ? $z = "true\n" : ($z = "false\n"); print $z; # my preferred version $z = $x ? "true\n" : "false\n"; print $z;
      say $x ? "true" : "false";

      And it's called the conditional operator. It is merely a ternary operator, just like addition operator is a binary operator. It not even Perl's only ternary operator.

        It not even Perl's only ternary operator.

        ???