Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #206 Switch statement with strings

Execute different procedures foo, bar, baz and barfl if the string str contains the name of the respective procedure. Do it in a way natural to the language.

my %proc = map { $_ => \&$_ } qw(foo bar baz barfl);
$proc{$str}->() if exists $proc{$str};

Hash _%proc is assigned pairs of values by iterating over the word list created by qw() using map.

Within the block { }, the pairs are created by using the fat-comma operator (=>) to form keyword/value pairs using the loop element ($_) as the keyword value on the left and to form a subroutine reference (\&$_) on the right.

%proc becomes a dispatch table with entries like 'foo' => \&foo. sub foo must exist.

Note that names are specified without repetition.
(some-> str {"foo" foo "bar" bar "baz" baz "barfl" barfl} (.call))

map is a function of a key, which return value for that key, if any.

There is case, but unlike map {} it is opaque, and you can't see which functions are whitelisted in runtime.

.call is a java.util.concurrent.Callable/call

New implementation...
< >
tkoenig