in reply to Improving if statements

my %stuff = ( moo => "cow", test => "blue", dark => "black", white => "light", house => "home", "all things" => "multi", money => "value", country => "Well, not Scotland apparently" ); my $whoopdie = $stuff{param("item")} || "NAOAOAOANOOOO!!!"; print "Final Item = $whoopdie";

Replies are listed 'Best First'.
Re^2: Improving if statements
by choroba (Cardinal) on Sep 18, 2014 at 23:40 UTC
    Hash, unlike if, has no order. If the order matters, you might need something like the following (alternatives in regexes match from the leftmost one):
    my @keys = ('test', 'dark', 'white', 'house', 'all things', 'money', 'count +ry'); my @values = qw(blue black light home multi value USA); my $regex = join '|', @keys; # "map quotemeta" might be needed for ugl +ier keys $regex = qr/($regex)/; my %switch; @switch{@keys} = @values; my $change; if ($item =~ $regex) { $change = $switch{$1}; } else { $change = "neutral"; } print "Final Item = $change.\n";
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Order will not matter, I am more concerned about speed.
Re^2: Improving if statements
by Anonymous Monk on Sep 18, 2014 at 23:40 UTC
    I liked it!
    I just fixed this line for future reference:

    From this:
    my $whoopdie = $stuff{param("item")} || "NAOAOAOANOOOO!!!";
    To:
    my $whoopdie = $stuff{$q->param("item")} || "NAOAOAOANOOOO!!!";

    Thanks for the helping!

      It’s fine of course but using CGI.pm as OO has always struck me really silly (UNLESS you’re passing the object to other code). use CGI ":standard"; param(); La.