【发布时间】:2014-03-19 23:06:23
【问题描述】:
我想知道为什么下面的语法会失败
#!/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";
【问题讨论】:
-
只要你有一个多层数据结构,就会在层之间假设取消引用箭头
->。换句话说,$array[1](2)与$array[1]->(2)相同。 -
&$addref(5)可以正常工作。
标签: perl reference anonymous-methods