Perl,`map` 函数的未知结果

Perl, unknown result of the `map` function

我在下面的 print @squares 数组中得到了一个非常奇怪的结果; 我应该得到 49,但我得到了一些随机数:

@numbers={-1,7};

my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;

print @squares;

$ perl g.pl

12909907697296

您的行 @numbers={-1,7} 没有创建多个整数的列表。在 Perl 中,带花括号的表达式表示 散列引用文字 。这可以写得更清楚:

my @numbers = ({ "-1" => 7 });

所以这是一个包含一项的列表,它是一个哈希引用。

稍后,您将哈希引用用作数字。当您将引用用作数字时,它会转换为其内存地址,这是一些未指定的大数。这就是您所看到的。

要在 Perl 中创建包含范围,请使用 .. 运算符:

my @numbers = -1..7;

要拼出列表中的所有项目,请将其括在括号中 ( ):

my @numbers = (-1, 7);

这是不正确的:

@numbers={-1,7};

{ } 构建散列和 returns 对散列的引用。以上相当于

my %anon = ( -1 => 7 );
@numbers = \%anon;

引用被视为数字returns底层指针被视为数字,所以你会得到垃圾。


要填充数组,请使用

my @numbers = ( -1, 7 );

-1, 7 returns两个数,给数组赋值的时候加到数组中。 (括号并不特殊;它们只是像数学中一样覆盖优先级。)


完整程序:

use 5.014;      # ALWAYS use `use strict;` or equivalent! This also provides `say`.
use warnings;   # ALWAYS use `use warnings;`!

my @numbers = ( -1, 7 );

my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;

# Print each number on a separate line.
# Also provides the customary final line feed.
say for @squares;

选择:

my @squares =
   map { $_ * $_ }
      grep { $_ > 5 }
         @numbers;