gpt4 book ai didi

perl - 计算数组中的唯一值不起作用

转载 作者:行者123 更新时间:2023-12-02 06:02:11 25 4
gpt4 key购买 nike

这是我的代码,用于计算 perl 数组中的 uniq 值并将它们放入哈希数组中

@array=$_[0];

print Dumper @array;

my %counts;

$counts{$_}++ for @array;
print Dumper(\%counts);

输出是:

$VAR1 = [
-46,
'53',
11,
'84',
-2,
'47',
-7,
'72',
0,
'14',
-10,
'3',
-46,
'53',
11,
'84',
-2,
'47',
-7,
'72',
0,
'14',
-10,
'3'
];
$VAR1 = {
'ARRAY(0x180c844)' => 1
};

为什么哈希数组是空的??以及如何计算 uniq 值?

最佳答案

$_[0] 中有一个数组引用,Data::Dumper 输出显示了这一点

$VAR1 = [ ....
# ^-- array ref

所以当你这样做的时候

$counts{$_}++ for @array;

您正在对数组 ref 进行字符串化,它变成 ARRAY(0x180c844) 或类似的东西,然后它的键递增。

如何修复:取消引用 $_[0]。复制到数组或直接使用。

@array = @{$_[0]};

$counts{$_}++ for @{$_[0]};

您应该注意,在检查唯一数字时,如果看起来不同的数字应该被认为是相同的,您可能会遇到问题,例如1.01。您可能希望事先规范化数字,如下所示:

$counds{ 0+$_ }++ for @array;

关于perl - 计算数组中的唯一值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com