Variable variable name

matthew wickline m_pm_pdx at
Wed Jul 3 20:32:05 CDT 2002

Jason White <jasona at> wrote:
> my $functionToCall = "foo";
> ???????( );
> sub foo( ){  print "FOO!\n";  };

I think you may want 

    use strict;
    my $todo = "foo";
    my %funcs = ( # hash of subroutine references
        'foo' => sub { print "FOO!"; },
        'bar' => sub { print "BAR!"; },
        'baz' => sub { print "BAZ!"; },
    &{ $funcs{$todo} };   # or   $funcs{$todo}->();

or maybe you want

    use strict;
    my $todo = "foo";
    sub foo() { print "FOO!"; }
    sub bar() { print "BAR!"; }
    sub baz() { print "BAZ!"; }
    my %funcs = ( # hash of subroutine references
        'foo' => \&foo,
        'bar' => \&bar,
        'baz' => \&baz,
    &{ $funcs{$todo} };   # or   $funcs{$todo}->();

do either of those seem like they'd work for you?

see also:
        The first example above uses the
            sub BLOCK
        what you're trying to do in the original form is
        a violation of stricture (unless you want to do
        it in a particularly funky way) because that sort
        of practice is more likely to lead to accidental
        errors that are difficult to track down.
        the first is a quick tutorial on references but
        doesn't address subroutine references. Once you've
        got a handle on references to scalars, arrays and
        hashes, move onto the second one for more info on
        references. ... more links provided from those



More information about the Pdx-pm-list mailing list