如何在Perl中调用名称为哈希值的子例程?

Laz*_*zer 6 perl hash subroutine

$ cat test.pl
use strict;
use warnings;

sub route {
    print "hello, world!";
}

my %h;
$h{'a'} = 'route';

print "1\n";
$h{a};

print "2\n";
$h{a}();

print "3\n";
"$h{a}".();
$ perl test.pl
Useless use of hash element in void context at test.pl line 12.
Useless use of concatenation (.) or string in void context at test.pl line 18.
1
2
Can't use string ("route") as a subroutine ref while "strict refs" in use at test.pl line 15.
$
Run Code Online (Sandbox Code Playgroud)

什么是正确的打电话方式route()

Dav*_*oss 13

您正尝试使用$ h {a}作为符号引用.并且"使用严格"明确禁止这一点.如果你关闭严格模式,那么你可以这样做:

no strict;
&{$h{a}};
Run Code Online (Sandbox Code Playgroud)

但最好的方法是在哈希中存储子程序的"实际"引用.

#!/usr/bin/perl

use strict;
use warnings;

sub route {
    print "hello, world!";
}

my %h;
$h{a} = \&route;

$h{a}->();
Run Code Online (Sandbox Code Playgroud)

  • 虽然我完全同意davorg关于使用代码引用的建议,但我也想指出perl的"can"功能.给定函数所在的包的名称和函数名称本身,它可以使用`$ package-> can($ function)`检索该函数的代码引用,而不必关闭严格的引用. (3认同)
  • "没有严格的'参考'就足够了. (2认同)