我想知道为什么以下语法失败
#!/usr/bin/env perl
use warnings;
use strict;
sub add { return $_[0]+5; };
my $add_ref = \&add;
my $result = 0;
$result = &add(5);
print " result is $result \n";
$result = add(5);
print " result is $result \n";
#$result = $add_ref(5); ---------------> fail
#print " result is $result \n";
#$result = {$add_ref}(5); -----------------> fail
#print " result is $result \n";
$result = &{$add_ref}(5);
print " result is $result \n";
$result = $add_ref->(5);
print " result is $result \n";
1) 我刚刚将函数 add
的名称替换为 {$add_ref}
,这是中级 Perl 书中提到的方法。在函数调用中 &
是可选的,但在本例中为什么不呢?
2)我还发现 $reference_to_anonymous_subroutine(parameter)
有效,但 $reference_to_names_subroutine(parameter)
示例
my @array = (1, sub { my $n = $_[0]; $n = $n +5;});
my $result = $array[1](2); ---------> works and does not need &{$array[1]}(2)
print "$result \n";
最佳答案
In a function call
&
is optional, but why not in this case.
在子例程中,调用 &
是可选的,但仅当您已经拥有子例程时,而不是当您需要首先取消引用它时。
取消引用某些内容的首选方法是 ->
符号。
$subroutine_ref->(5);
$hash_ref->{'key'};
$array_ref->[5];
当然TIMTOWTDI ,并且您可以使用键入的符号而不是 ->
取消引用:
&$subroutine_ref(5); # same effect as $subroutine_ref->(5)
但我发现它的可读性较差。
my $result = $array[1](2); # works and does not need &{$array[1]}(2)
如果这深入多个级别,则各部分之间的 ->
是隐含的且可选的。
$array[1](2); # shorthand for $array[1]->(2);
不过,您可能仍然需要第一个:如果您有数组引用而不是数组,则需要这样做
$array_ref->[1](2);
关于perl - 取消引用子例程语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22520074/