Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: if else in the other way

by biohisham (Priest)
on Oct 02, 2010 at 10:29 UTC ( [id://863061]=note: print w/replies, xml ) Need Help??


in reply to if else in the other way

Or you can use this which is essentially similar to jwkrahn's but a little bit more readable in this context
$a == 6 ? print "yes\n" : print "no\n";


Excellence is an Endeavor of Persistence. A Year-Old Monk :D .

Replies are listed 'Best First'.
Re^2: if else in the other way
by johngg (Canon) on Oct 02, 2010 at 12:12 UTC
    but a little bit more readable

    Debatable :-)

    For a simple yes/no print like this you are probably right. For lengthier outputs with, perhaps, a conditional part in the middle your way involves a lot of repeated text which can obscure meaning. Personally, in such cases I find this layout

    print qq{Fixed part }, ( conditional expression ) ? qq{True part } : qq{False part }, qq{Further fixed text here\n};

    more readable than this

    ( conditional expression ) ? print qq{Fixed part True part Further fixed text here\n} : print qq{Fixed part False part Further fixed text here\n};

    particularly if the condition doesn't require parentheses, but others will probably disagree. I would be more likely to write the latter using an if ( ... ) { ... } else { ... } construct anyway as the meaning is more widely familiar.

    Cheers,

    JohnGG

      I agree ;), and I agree that this is debatable, I am a fan of not repeating commands while using a ternary operator too, in fact, avoiding ternary operators all together should my code be maintained by someone else, however, my answer was relative to this simple requirement put forth by the OP, breaking jwkrahn's reply down for him/her.


      Excellence is an Endeavor of Persistence. A Year-Old Monk :D .
Re^2: if else in the other way
by eyepopslikeamosquito (Archbishop) on Oct 02, 2010 at 22:01 UTC

    Compared to jwkrahn's simple and clear version (with one print), this "improvement" (with print occurring twice) is a violation of the DRY principle.

    See also Perl Best Practices: Chapter 6 (Control Structures), Tabular Ternaries; and Chapter 2 (Code Layout), Ternaries.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2025-02-08 03:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which URL do you most often use to access this site?












    Results (95 votes). Check out past polls.