How can I elegantly call a Perl subroutine whose name is held in a variable?

Perl

Perl Problem Overview


I keep the name of the subroutine I want to call at runtime in a variable called $action. Then I use this to call that sub at the right time:

&{\&{$action}}();

Works fine. The only thing I don't like is that it's ugly and every time I do it, I feel beholden to add a comment for the next developer:

# call the sub by the name of $action

Anyone know a prettier way of doing this?


UPDATE: The idea here was to avoid having to maintain a dispatch table every time I added a new callable sub, since I am the sole developer, I'm not worried about other programmers following or not following the 'rules'. Sacrificing a bit of security for my convenience. Instead my dispatch module would check $action to make sure that 1) it is the name of a defined subroutine and not malicious code to run with eval, and 2) that it wouldn't run any sub prefaced by an underscore, which would be marked as internal-only subs by this naming convention.

Any thoughts on this approach? Whitelisting subroutines in the dispatch table is something I will forget all the time, and my clients would rather me err on the side of "it works" than "it's wicked secure". (very limited time to develop apps)


FINAL UPDATE: I think I've decided on a dispatch table after all. Although I'd be curious if anyone who reads this question has ever tried to do away with one and how they did it, I have to bow to the collective wisdom here. Thanks to all, many great responses.

Perl Solutions


Solution 1 - Perl

Rather than storing subroutine names in a variable and calling them, a better way to do this is to use a hash of subroutine references (otherwise known as a http://perldesignpatterns.com/?DispatchTable">dispatch table.)

my %actions = ( foo => \&foo,
                bar => \&bar,
                baz => sub { print 'baz!' } 
                ... 
              );

Then you can call the right one easily:

$actions{$action}->();

You can also add some checking to make sure $action is a valid key in the hash, and so forth.

In general, you should avoid symbolic references (what you're doing now) as they cause all kinds of problems. In addition, using real subroutine references will work with strict turned on.

Solution 2 - Perl

Just &$action(), but usually it's nicer to use coderefs from the beginning, or use a dispatcher hash. For example:

my $disp = {foo => \&some_sub, bar => \&some_other_sub };
$disp->{'foo'}->();

Solution 3 - Perl

Huh? You can just say

    $action->()

Example:

    sub f { return 11 }
    $action = 'f';
    print $action->();


    $ perl subfromscalar.pl
    11

Constructions like

    'f'->()     # equivalent to   &f()

also work.

Solution 4 - Perl

I'm not sure I understand what you mean. (I think this is another in a recent group of "How can I use a variable as a variable name?" questions, but maybe not.)

In any case, you should be able to assign an entire subroutine to a variable (as a reference), and then call it straightforwardly:

# create the $action variable - a reference to the subroutine
my $action = \&preach_it;
# later - perhaps much later - I call it
$action->();

sub preach_it {
    print "Can I get an amen!\n"
}

Solution 5 - Perl

The most important thing is: why do you want to use variable as function name. What will happen if it will be 'eval'? Is there a list of functions that can be used? Or can it be any function? If list exists - how long it is?

Generally, the best way to handle such cases is to use dispatch tables:

my %dispatch = (
   'addition' => \&some_addition_function,
   'multiplication' => sub { $self->call_method( @_ ) },
);

And then just:

$dispatch{ $your_variable }->( 'any', 'args' );

Solution 6 - Perl

__PACKAGE__->can($action)->(@args);

For more info on can(): http://perldoc.perl.org/UNIVERSAL.html

Solution 7 - Perl

I do something similar. I split it into two lines to make it slightly more identifiable, but it's not a lot prettier.

my $sub = \&{$action};
$sub->();

I do not know of a more correct or prettier way of doing it. For what it's worth, we have production code that does what you are doing, and it works without having to disable use strict.

Solution 8 - Perl

Every package in Perl is already a hash table. You can add elements and reference them by the normal hash operations. In general it is not necessary to duplicate the functionality by an additional hash table.

#! /usr/bin/perl -T
use strict;
use warnings;

my $tag = 'HTML';

*::->{$tag} = sub { print '<html>', @_, '</html>', "\n" };

HTML("body1");

*::->{$tag}("body2");

The code prints:

<html>body1</html>
<html>body2</html>

If you need a separate name space, you can define a dedicated package.

See perlmod for further information.

Solution 9 - Perl

Either use

&{\&{$action}}();

Or use eval to execute the function:

eval("$action()");

Solution 10 - Perl

I did it in this way:

@func = qw(cpu mem net disk);
foreach my $item (@func){
	$ret .= &$item(1);
}

Solution 11 - Perl

If it's only in one program, write a function that calls a subroutine using a variable name, and only have to document it/apologize once?

Solution 12 - Perl

I used this: it works for me.

(\$action)->();

Or you can use 'do', quite similar with previous posts:

$p = do { \&$conn;}; 
$p->();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcusView Question on Stackoverflow
Solution 1 - PerlfriedoView Answer on Stackoverflow
Solution 2 - PerlHarmenView Answer on Stackoverflow
Solution 3 - PerlmobView Answer on Stackoverflow
Solution 4 - PerlTelemachusView Answer on Stackoverflow
Solution 5 - Perluser80168View Answer on Stackoverflow
Solution 6 - PerlNehal J WaniView Answer on Stackoverflow
Solution 7 - PerlWesView Answer on Stackoverflow
Solution 8 - PerlcevingView Answer on Stackoverflow
Solution 9 - PerlGrolimView Answer on Stackoverflow
Solution 10 - PerlPutnikView Answer on Stackoverflow
Solution 11 - PerlDean JView Answer on Stackoverflow
Solution 12 - PerlYangView Answer on Stackoverflow