Kashratul has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I like to put forward a question:

Is is possible to make the name of a subroutine dynamic i.e.

let us assume that we have a variable = $a

now I want to name a subroutine with the value of the variable

So if the $a value is "TYPE" - then subroutine name changes to Type

If the $a value is "CLICK" - then subroutine name changes to CLICK

I am not sure whether this is at all possiable - I just want advise whether this can be done if so how

Thanks for your time

  • Comment on Initializing a subroutine with the value of a variable

Replies are listed 'Best First'.
Re: Initializing a subroutine with the value of a variable
by holli (Abbot) on Dec 17, 2009 at 15:10 UTC
    sub foo { print 'bar' } $var = 'foo'; main->$var;
    However, this calls "foo" as a class method, so the sub gets the classname as the first argument. If you dont want that, use a dispatch table.
    %subs = ( 'foo' => \&foo, 'bar' => \&bar, # etc ); print $subs{$var}->($arg1, $arg2);


    holli

    You can lead your users to water, but alas, you cannot drown them.
Re: Initializing a subroutine with the value of a variable
by The Perlman (Scribe) on Dec 17, 2009 at 23:41 UTC
    Yes it's possible but for good reasons it's not recommended!

    That's why it's not allowed with use strict so you need to disable strict locally!

    use strict; our $a="func"; sub func {print shift}; { no strict 'refs'; &$a(42); }
    But this approach should only be the last possible choice!

    hollis solution is much cleaner and defining a dispatch table can be done in a very compact way:

    my %dispatch=( func1 => sub { print shift }, func2 => sub { print 1+ shift }, ); $dispatch{func1}->(42);
Re: Initializing a subroutine with the value of a variable
by Anonymous Monk on Dec 17, 2009 at 14:47 UTC