perl - 子程序调用前的反斜杠

标签 perl reference subroutine

因为我在理解 [] 和\在引用文献中的区别,所以我在子例程中都使用了前者很好但是当我稍后尝试时我认为它应该给出错误但是下面的 perl 程序

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @b;
for my $i ( 0 .. 10 ) {
    $b[$i] = \somefunc($i);

}
print Dumper( \@b );

sub somefunc {
    my $n = shift;
    my ( @a, $k );
    for my $j ( 11 .. 13 ) {
        $k = $n * $j;
        push( @a, $k );
    }
    print "a: @a \n";
    return @a;
}

输出为:

a: 0 0 0 
a: 11 12 13 
a: 22 24 26 
a: 33 36 39 
a: 44 48 52 
a: 55 60 65 
a: 66 72 78 
a: 77 84 91 
a: 88 96 104 
a: 99 108 117 
a: 110 120 130 
$VAR1 = [
      \0,
      \13,
      \26,
      \39,
      \52,
      \65,
      \78,
      \91,
      \104,
      \117,
      \130
    ];

我无法理解输出。需要解释。

最佳答案

这里发生的是:

您正在从 somefunc 返回一个数组。

但是您将其分配给一个标量。因此,这有效所做的只是将数组中的最后一个值放入标量值中。

my $value =  ( 110, 120, 130 );
print $value;

执行此操作时 - $value 设置为数组中的最后一个值。这就是您的代码中实际发生的情况。参见示例 perldata :

List values are denoted by separating individual values by commas (and enclosing the list in parentheses where precedence requires it): (LIST)

In a context not requiring a list value, the value of what appears to be a list literal is simply the value of the final element, as with the C comma operator. For example,

@foo = ('cc', '-E', $bar);

assigns the entire list value to array @foo, but

foo = ('cc', '-E', $bar);

assigns the value of variable $bar to the scalar variable $foo. Note that the value of an actual array in scalar context is the length of the array; the following assigns the value 3 to $foo:

@foo = ('cc', '-E', $bar); $foo = @foo; # $foo gets 3

后一种情况通常是陷阱,因为它是标量上下文中的列表。

在您的示例中 - 反斜杠前缀表示“对”的引用 - 这在很大程度上没有意义,因为它是对数字的引用。

但对于标量,它可能更有意义:

my $newvalue = "fish"; 
my $value =  ( 110, 120, 130, \$newvalue );
print Dumper $value;

$newvalue = 'barg'; 
print Dumper $value;

给予:

$VAR1 = \'fish';
$VAR1 = \'barg';

这就是您获得结果的原因。带有斜杠的前缀表示您正在获取对结果的引用,而不是对子项的引用。对 130 的引用实际上并不是那么有意义。

通常,在执行上述赋值时 - 您会收到关于 Useless use of a constant (110) in void context 的警告,但当您有子例程返回时,这并不适用.

如果你想插入一个 sub 引用,你需要添加 &,但如果你只是想通过引用插入返回的数组 - 你要么需要到:

$b[$i] = [somefunc($i)]

或者:

return \@a;

关于perl - 子程序调用前的反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641879/

相关文章:

Catalyst 对 Perl 5.8.8 的支持

perl - 将 IPC::Open3 与 perlcritic 一起使用

multithreading - ForkManager 在 Debug模式下完成得更快

perl - 强制 YAML::Tiny 值为数字

java - 为什么我可以使用类引用交换类内的字段值,但不能交换引用本身

perl - Perl子例程如何报告调用它的行?

c++ - const ref lvalue to non-const func return value 是否专门减少拷贝?

c++ - sizeof 对 gdb 中数组的引用

algorithm - 施特拉森矩阵乘法

perl - 通过命令提示符执行 Perl 子例程?