Philip Potter wrote:
2009/9/11 Uri Guttman <u...@stemsystems.com>:
"SB" == Steve Bertrand <st...@ibctech.ca> writes:
SB> Besides consistently forgetting how to properly spell "ternary", I
SB> can't, for some reason, embed it's use into my brain no matter how
SB> much I read.
ternary op is an official name but it has many nicknames so they are
worth knowing too. conditional expression is longer but very
descriptive. hook/colon is a slang name.
it is actually very simple to understand. the key point to knowing it
and how to use it is that the 2 value expressions SHOULD NOT have side
effects. that means changing something by assignment or other
modification. your example below is one exception to that.
Does ?: guarantee that only one arm of its conditions will be executed? eg:
# @_ has 3 elements
$x = $flag ? shift : push;
$ perl -e'$x = $flag ? shift : push;'
Not enough arguments for push at -e line 1, near "push;"
Execution of -e aborted due to compilation errors.
Perhaps you meant:
$x = $flag ? shift : pop;
# is it now guaranteed that @_ has 2 elements?
Yes, if you write it that way instead. Or:
$x = splice @_, $flag ? 0 : -1, 1;
In the above example, is it guaranteed that *either* shift *or* push
happens, but *not* both?
Yes, either shift() or pop() happens, but not both.
perl won't calculate both sides in advance
and assign only one to $x?
$ perl -le'
my $flag = $ARGV[ 0 ];
sub my_shift { warn "In my_shift sub\n"; return shift @ARGV }
sub my_pop { warn "In my_pop sub\n"; return pop @ARGV }
my $x = $flag ? my_shift() : my_pop();
print qq/\$x = "$x"/;
' one two three four five six
In my_shift sub
$x = "one"
$ perl -le'
my $flag = $ARGV[ 0 ];
sub my_shift { warn "In my_shift sub\n"; return shift @ARGV }
sub my_pop { warn "In my_pop sub\n"; return pop @ARGV }
my $x = $flag ? my_shift() : my_pop();
print qq/\$x = "$x"/;
' 0 one two three four five six
In my_pop sub
$x = "six"
Nope, only one "side" is evaluated.
I ask because this is the behaviour I expect from C and C++, it's very
important (Steve's original ? shift : {} is broken without it), but
it's not explicitly stated in perldoc perlop. perlop *does* explain
the short-circuit behaviour of qw(|| && // or and) and their use for
control flow, but is silent on ?:'s control flow behaviour. Is this
documented in perldoc, and if so where?
Operators borrowed from C keep the same precedence
relationship with each other, even where C’s precedence is
slightly screwy. (This makes learning Perl easier for C folks.)
Conditional Operator
Ternary "?:" is the conditional operator, just as in C. It works
much like an if-then-else. If the argument before the ? is true,
the argument before the : is returned, otherwise the argument
after the : is returned.
John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/