[Omaha.pm] precedence: ?: vs. =

Jay Hannah jhannah at omnihotels.com
Fri Jun 3 09:48:53 PDT 2005


This doesn't do what the author was expecting:

  $_[1] ? $prop_to_ping = $_[1] : $prop_to_ping = $_[0]->{prop};

Because = binds tighter than :

So, avoid this pattern

   $a ? $x = $a : $x = $b;

Instead, use patterns 2-4 below. I like 4, but that's just me.

j


-----------------
$ cat j2.pl
use Test::More tests => 4;

$a = 10;
$b = 20;

$a ? $x = $a : $x = $b;
is ($x, 10, "Pattern 1");
$a ? ($x = $a) : ($x = $b);
is ($x, 10, "Pattern 2");
$x = $a ? $a : $b;
is ($x, 10, "Pattern 3");
$x = $a || $b;
is ($x, 10, "Pattern 4");

$ perl j2.pl
1..4
not ok 1 - Pattern 1
#     Failed test (j2.pl at line 7)
#          got: '20'
#     expected: '10'
ok 2 - Pattern 2
ok 3 - Pattern 3
ok 4 - Pattern 4
# Looks like you failed 1 tests of 4.
-----------------



More information about the Omaha-pm mailing list