Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Improving if statements

by biohisham (Priest)
on Sep 19, 2014 at 05:15 UTC ( [id://1101152]=note: print w/replies, xml ) Need Help??


in reply to Improving if statements

Multiple if statements are really redundant, that is true, but not necessarily a bad thing unless readability of the code becomes difficult. I find the solutions by Your Mother and choroba to be very educational, succinct and efficient. It may be also relevant to include the utility of the Switch module for tasks like testing different cases and responsing to each case.

use strict; use warnings; use Switch; my $item = $ARGV[0]; switch($item){ case "moo" {print "cow"} case "test" {print "blue"} case "dark" {print "black"} case "white" {print "light"} case "house" {print "home"} case "all things" {print "multi"} case "money" {print "value"} case "country" {print "Well, not Scotland apparently"} else {print "NAOAOAOANOOOO!!!" } }
UPDATE: The use of switch statements in the way I recommended may not be a favorable option judging by the amount of downvotes my reply received. Thanks Tobylink for elaborating on problems with Switch statements, I definitely learned something new about them.

David R. Gergen said "We know that second terms have historically been marred by hubris and by scandal." and I am a two y.o. monk today :D, June,12th, 2011...

Replies are listed 'Best First'.
Re^2: Improving if statements
by tobyink (Canon) on Sep 19, 2014 at 05:53 UTC

    Don't recommend Switch please. The abstract in its documentation says (my emphasis):

    A switch statement for Perl, do not use if you can use given/when

    It continues:

    There are undoubtedly serious bugs lurking somewhere in code this funky :-) Bug reports and other feedback are most welcome.

    May create syntax errors in other parts of code.

    On perl 5.10.x may cause syntax error if "case" is present inside heredoc.

    In general, use given/when instead. It were introduced in perl 5.10.0. Perl 5.10.0 was released in 2007.

    The given and when keywords were introduced in Perl 5.10. They are experimental, and will warn on some versions of Perl (unless you disable that warning), but still a lot more reliable than Switch.

    There's also Switch::Plain and Switcheroo on CPAN.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-03-28 20:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found