Uri Guttman wrote:

Thanks to all for the fantastic feedback, and for the very detailed
examples. After reading and practising them a few times, I don't think
I'll ever be able to forget how to use this op anymore :)

> 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.

Since I use functions/methods to perform side effects frequently, I
believe what you mean is that in *most* cases, the conditional op
shouldn't ever have anything that must be evaluated in one of the
either/or fields.

For example, this:

my $num    = 1;
my $add_to = 2;

my $ret = ( $foo == 1 ) ? ( $num + $add_to ) : 2;

...SHOULD _always_ ( where possible ) be written as:

my $expr_result = ( $num + $add_to );

my $ret = ( $foo == 1 ) ? $expr_result : 2;

> whenever you see an if/else where the code just assigns one or another
> value to the same variable that should be coded as a ternary op as this
> is what is it designed to do:
> 
>       $gst = ( $gst eq 'Yes' ) ? $self->tax_rate( 'gst' ) : 0 ;
> 
> now, using the same variable $gst for the input and then a value is
> slightly dodgy IMO.

I agree completely with the "dodgy" comment. In fact, at the same time
I'm writing new code, I'm noticing "red flags" in adjacent code, and
changing it as I go. The more I learn, the more I'm changing.

Recently, I was bit by a self-induced 'bug' by doing something very
similar, and it took hours to track down. ( may as well vent about my 12
hour, a full day and a half to track problem, simply by having a
forgotten-about global variable. Code goes > 600 lines, and results were
far from what I expected. I noticed the global var in a diff in passing,
removed it, and voila... ).

> this is common dumbass code as it breaks what
> the conditional op is for and also breaks the code because of
> precedence:
> 
>       ( $foo == 0 ) ? $bar = 1 : $bar = 2 ;
> 
> i won't go deeper into the precedence bug but instead focus on the
> dumbass part. why is that coded assigning to the same var inside the ?:
> ? the whole point of ?: is to get a value from one of two choices to
> USE. so that should be written as:
> 
>       $bar = ( $foo == 0 ) ? 1 : 2 ;

I definitely get it now :)

Thanks for the straight-up explanation.

...and thanks John for all of the different examples.

Cheers!

Steve

Attachment: smime.p7s
Description: S/MIME Cryptographic Signature

Reply via email to