Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Perl/Unix case

by Elgon (Curate)
on Oct 22, 2004 at 17:45 UTC ( #401593=note: print w/replies, xml ) Need Help??

in reply to Perl/Unix case

Your suggestion was a good one IMHO, or at least very close to being good - look up dispatch tables and/or coderefs in super search and you should find something. They are a useful and elegant way of handling this kind of problem.

UPDATE: Look here for a small hint on the use of dispatch tables. Code also added below...

my $foo; my $bar; my @args; # Get $foo $bar and @args somewhere around here... my %despatch_table = ("one" => ( "alpha" => \&func_onealpha, "beta" => \&func_onebeta), "two" => ("alpha" => \&func_twoalpha, "beta" => \&func_twobeta)); my $answer; if ($answer = &${$despatch_table{$foo}}{bar}(@args)) { # Do something with $answer } else { # Bad values throw an error } sub func_onealpha { # Do stuff here } sub func_onebeta { # Do stuff here } sub func_twoalpha { # Do stuff here } sub func_twobeta { # Do stuff here }

You use the string values of $foo and $bar as keys to the hash, which contains references to subroutines (in this case named, but can be anonymous subs in the hash itself. This is a bit of a rigmarole to go through, but ends up being better to work with than a huge nest of if statements.


It is better either to be silent, or to say things of more value than silence. Sooner throw a pearl at hazard than an idle or useless word; and do not say a little in many words, but a great deal in a few.

Pythagoras (582 BC - 507 BC)

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (None)
    As of 2021-10-20 01:59 GMT
    Find Nodes?
      Voting Booth?
      My first memorable Perl project was:

      Results (78 votes). Check out past polls.