in reply to Invoke sub whose name is value of scalar

At some point in their life, every programmer decides that, for the problem at hand, the best solution is to create a set of functions and pass their names as variables. It's not.
First, its a security hazard, as users' input should never be used to execute code in your programs. Second, since code doesn't write itself, the functions themselves have to be written and named, so the actual "variable named after function/function named after variable" scheme isn't much different than foo() if (/foo/).
This pseudo-"functional programming" is better written as a hash with the variable name as key and a function ref as value, similar (but not limited) to this example:

use strict; use warnings; my %hash = ( foo => sub {return "foo\n"}, bar => sub {return "bar\n"}, ); print &{$hash{'foo'}};

Also, with single quotes, 'foo\n' prints foo\n rather than "foo" and a newline.

Software speaks in tongues of man.
Stop saying 'script'. Stop saying 'line-noise'.
We have nothing to lose but our metaphors.

Replies are listed 'Best First'.
Re^2: Invoke sub whose name is value of scalar
by ysth (Canon) on Apr 15, 2008 at 07:10 UTC
    I saw the root node's title and the number of replies and without even looking at the content figured people were demonstrating lots of different ways to do dispatch tables. Then actually reading the thread, I saw no dispatch tables at all, until the very last reply, by Erez.

    Better late than never :)

    If (as I guess from the OP's update) the subs do more than one-line of work, you can still use a dispatch table, but arranged like:

    sub foo { ... } sub bar { ... } my %hash = ( foo => \&foo, bar => \&bar, ); $var = "foo"; &{$hash{$var}}(@args);