引用带有标量的子例程

Refer to a subroutine with a scalar

是否可以使下面的示例起作用,以便通过标量变量存储和调用子例程的名称?

use strict;
use warnings;

sub doit {
    my ($who) = @_;
    print "Make us some coffee $who!\n";
}

sub sayit {
    my ($what) = @_;
    print "$what\n";
}

my $action = 'doit';
$action('john');

你可以把它放在一个散列中:

my %hash;
$hash{'doit'} = \&doit;
$hash{'doit'}->('Mike');

或者您可以立即将其设为匿名子

my %hash = ( doit  => sub {  ... },
             sayit => sub { .... },
            ....);

达达说的是标量值,所以也可以放在标量变量中:

my $command = \&doit;
$command->('Mike');

从技术上讲,您还可以将字符串放入标量中,并将其用作子例程:

my $action = 'doit';
$action->('Mike');      # breaks strict 'refs'

但是如果你正在使用 use strict,就像你应该的那样,它不会允许你,并且会死于错误:

Can't use string ("doit") as a subroutine ref while "strict refs" in use...

所以不要那样做。如果你想使用字符串来引用 subs,使用散列是正确的方法。但如果你还想,你可以

no strict 'refs';

逃避它。

根据这个问题的回答: How can I elegantly call a Perl subroutine whose name is held in a variable?

你可以试试这个:

__PACKAGE__->can($action)->('john');