如何将数组初始化为 0?
我试过这个。
my @arr = ();
但它总是向我发出警告,“使用未初始化的值”。我事先不知道数组的大小。我动态填充它。我认为上面的代码应该将其初始化为 0。
我该怎么做呢?
最佳答案
如果我理解你,也许你不需要一个零数组;相反,您需要一个 哈希 .散列键将是另一个数组中的值,散列值将是该值在另一个数组中存在的次数:
use strict;
use warnings;
my @other_array = (0,0,0,1,2,2,3,3,3,4);
my %tallies;
$tallies{$_} ++ for @other_array;
print "$_ => $tallies{$_}\n" for sort {$a <=> $b} keys %tallies;
输出:
0 => 3
1 => 1
2 => 2
3 => 3
4 => 1
要更直接地回答您的特定问题,要创建一个填充了一堆零的数组,您可以在以下两个示例中使用该技术:
my @zeroes = (0) x 5; # (0,0,0,0,0)
my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
# This works because in scalar context
# an array evaluates to its size.
关于perl - Perl 中的数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3251495/