perl - 取消引用子例程语法

标签 perl reference anonymous-methods

我想知道为什么以下语法失败

 #!/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/

相关文章:

c# - 在类 C# 中使用 ref

HTML/CSS - 检查丢失的文件引用

delphi - 可选的匿名方法

delphi - 在 Delphi 2009 中类型转换匿名过程

perl - 从哈希引用中获取值

mysql - 当 Perl 错误地说 : `DBI->connect()` ? 时,如何将 "utf8mb4 is not a compiled character set"发送到 MySQL

perl - 如何在 Perl 中的线程之间共享文件句柄?

javascript - 上传文件大小限制为 32kB,我收到错误 "CGI.pm: Server closed socket during multipart read (client aborted?)."

C++ 通过引用传递

delphi - 存储匿名方法的容器