6
$ 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.
$

什么是正确的调用方式route()

4

2 回答 2

13

您正在尝试使用 $h{a} 作为符号引用。“使用严格”明确不允许这样做。如果你关闭严格模式,那么你可以这样做:

no strict;
&{$h{a}};

但最好的方法是在散列中存储对子例程的“真实”引用。

#!/usr/bin/perl

use strict;
use warnings;

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

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

$h{a}->();
于 2010-10-01T11:58:24.577 回答
3

您必须取消引用包含例程名称的字符串作为子项。括号是可选的。

my $name = 'route';
&{$name};

由于您的例程名称是哈希值,因此您必须从哈希中提取它。此外,当您使用时strict(这是一个很好的做法),您必须在本地禁用检查。

{
    no strict 'refs';
    &{$h{a}};
}

但是,正如 davorg 在他的回答中所建议的那样,最好(在性能方面)直接将对 sub 的引用存储在您的哈希中,而不是例程名称中。

于 2010-10-01T15:47:47.893 回答