in reply to if or switch?

Use a dispatch table. Something like...
my $mystring = "hello, I'm key2"; my %dispatcher = ( key1 => sub { print "1" }, key2 => sub { print "2" }, #... ); #... for my $key ( keys %dispatcher ) { $dispatcher{$key}->(), last if index($mystring, $key) >= 0; }


Unless I state otherwise, all my code runs with strict and warnings

Replies are listed 'Best First'.
Re^2: if or switch?
by Tanktalus (Canon) on Jul 10, 2008 at 22:56 UTC

    Using a hash here means you'll get the keys back in a random order. Which may be ok, but can fall down in two scenarios.

    First is if the keys can be subsets. e.g., if one is "key1" and another is "key10". You'll want to make sure you get them in order from longest to shortest. Easy enough to do:

    for my $key ( reverse sort {length $a <=> length $b} ) {
    This should be pretty fast. Can take a while for big lists, but then so can the index that we're about to run, so worrying about this O(N ln N) operation seems premature.

    The second failure is if you know that certain strings are more likely than others. So you can manually order the keys based on likelihood. This can really speed up the searches, too, if you're constantly short-circuiting things.

    This is why I opted, above, for a list of array refs instead of a hash.