Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Ternary operators: a hinderance, not a help

by phaylon (Curate)
on Aug 09, 2005 at 15:34 UTC ( [id://482257]=note: print w/replies, xml ) Need Help??


in reply to Ternary operators: a hinderance, not a help

I just use it when I find it is more readable. Sometimes I have things like
my $var = ( $EXPR ? sprintf( '...', $x ) : sprintf( '...', $y ) );

which I find more readable than a
my $var; if ( $EXPR ) { $var = sprintf( '...', $x ); } else { $var = sprintf( '...', $y ); }

I think it gives the possibility to keep together what should stand together. I also often found, that those real life scenarios you speak of are simpler to solve with the ternary operator, than with fully written conditionals.

But in the end, it's surely a question of personal preference :)

Ordinary morality is for ordinary people. -- Aleister Crowley

Replies are listed 'Best First'.
Re^2: Ternary operators: a hinderance, not a help
by graff (Chancellor) on Aug 10, 2005 at 01:12 UTC
    For that matter, if the "..." is the same in your two conditions, I'd do it like this:
    my $val = ( $EXPR ) ? $x : $y; my $var = sprintf( "...", $val );
    OTOH, if the "..." is different in each case, I might take the trouble to put that into a hash...
    my %format = ( $x => "... for x", $y => "... for y" ); my $val = ( $EXPR ) ? $x : $y; my $var = sprintf( $format{$val}, $val );
    And I agree with you and with earlier replies: it's a matter of personal preference for those of us who feel a sense of "semantic unity" in certain conditional assignments.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://482257]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-23 21:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found