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)