>>> "Brett W. McCoy" <[EMAIL PROTECTED]> 2/4/2002 9:28:42 PM >>>
>>On Mon, 4 Feb 2002, david wright wrote:
>>
>> i can't use the ternary operator like this? (damn waste if not) thanks.
>>
>> foreach $dup (@array){
>> (-d $dup) ? print "yes: $dup \n": print "no: $dup \n";
>> )
>
>Yes, that is an incorrect way to use the ?: operator -- the operataor is
>handed an expression that yields a boolean value, and it returns a value
>based on what that boolean value is:
>
> Here is a one liner that accomplishes what you want:
>
>$ perl -e '$ans = (-d "/usr/bin") ? "yes\n" : "no\n"; print $ans'
>yes
>
Actually, it is not an incorrect way I believe, so much as he is using slightly
incorrect syntax. From the Nutshell ...
<blockquote>
Ternary ?: is the conditional operator. It works much like an if-then-else statement,
but it can safely be embedded within other operations and functions.
test_expr ? if_true_expr : if_false_expr
If the test_expr is true, only the if_true_expr is evaluated. Otherwise, only the
if_false_expr is evaluated. Either way, the value of the _evaluated_expression_
becomes the value of the entire expression.
</blockquote>
.... I think the key is that he was not using a token that resulted in an explicit
evaluation, returning & capturing a result. By wrapping the 2nd and 3rd tokens of the
ternary clause in parens, this result can be acheived.
Here's an example I use often in CGIs to accomplish background-color swapping in HTML
table rows - achieiving an old computer-paper, green/white effect:
local $swapper = -1; # globals
local $bgcolor = '';
sub swapBGcolor {
(($swapper *= -1) > 0 ) ? ($bgcolor="#FFFFFF") : ($bgcolor="#F5DCC7");
}
Each time swapBGcolor is invoked, the value of $swapper is multiplied by -1, flipping
between +1 or -1. When that var is positive, the TRUE expression of the ternary
opertaor is 'evaluated', assigning a value to $bgcolor at the same time. When $swapper
is negative (false), the 2nd value of the global $bgcolor is assigned during the
'evaluation'.
I remember struggling with getting this to work and finally hitting upon using parens
to capture the result of an expression and returning it to the ? operator's result.
FYI
- John
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]