Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Ternary operators: a hinderance, not a help

by eric256 (Parson)
on Aug 09, 2005 at 19:14 UTC ( [id://482382]=note: print w/replies, xml ) Need Help??


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

I stayed away from ternary for a long time, but once you get use to it, it is a nice tool to have. It is certainly not a choice of either ternary or if, keep both in your tool box and you will be happy. I use ternary when they are simple cases like your example. It is ofter the most usefull for defaulting values and not creating several lines of if constructs. It is also usefull if you want to embed different things in a string.

print "You have $items " . ($items == 1 ? "object." : "objects.");

Certianly not the most poetic use of it, but it should demonstrate the use well enough. If you find your self using temporary variable and if structures, it might just be that you can use a tenrary to replace them. Now in that same example if i wanted to say "object(s)" more than once you can break it out int a single ternary:

my $objects = $items == 1 ? "object" : "objects"; print "You have $items $objects. What would you like to do with your $ +objects?";

And then if you I am going to change multiple variable based on the state of one, use an if. These are just my rules, guidlines, expereinces. Keep all your tools handy and sharp, because most things in perl fit somewhere, honest, they weren't just thrown in for the heck of it. Like any tool, if used wrong, they can do more damage than good. ;)


___________
Eric Hodges

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (1)
As of 2024-04-25 02:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found