Variable variable name

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


Jason White <jasona at inetarena.com> 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:

    http://www.perldoc.com/perl5.6.1/pod/func/sub.html
        The first example above uses the
            sub BLOCK
        form

    http://www.perldoc.com/perl5.6.1/lib/strict.html
        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.

    http://perldoc.com/perl5.6.1/pod/perlreftut.html
    http://perldoc.com/perl5.6.1/pod/perlref.html
        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
        resources.

    

-matt
TIMTOWTDI



More information about the Pdx-pm-list mailing list