【发布时间】:2021-06-20 22:04:39
【问题描述】:
我有一个包含某些值的 HoA。
我只需要拥有来自 HoA 的独特元素。
预期结果:
Key:1
Element:ABC#DEF
Key:2
Element:XYZ#RST
Key:3
Element:LMN
下面是我的脚本:
#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;
my %Hash = (
'1' => ['ABC', 'DEF', 'ABC'],
'2' => ['XYZ', 'RST', 'RST'],
'3' => ['LMN']
);
print Dumper(\%Hash);
foreach my $key (sort keys %Hash){
print "Key:$key\n";
print "Element:", join('#', uniq(@{$Hash{$key}})), "\n";
}
sub uniq { keys { map { $_ => 1 } @_ } };
脚本向我抛出以下错误:
Experimental keys on scalar is now forbidden at test.pl line 19.
Type of arg 1 to keys must be hash or array (not anonymous hash ({})) at test.pl line 19, near "} }"
Execution of test.pl aborted due to compilation errors.
如果我使用List::Util 的uniq 函数通过以下语句获取唯一元素,我可以得到想要的结果。
use List::Util qw /uniq/;
...
...
print "-Element_$i=", join('#', uniq @{$Hash{$key}}), "\n";
...
由于我在我的环境中安装了List::Util 的1.21 版本,它不支持uniq 功能,如List::Util documentation。
如何在不使用List::Util 模块的情况下获得所需的结果。
更新/编辑:
我通过在打印语句中添加这一行找到了解决方案:
...
print "Element:", join('#', grep { ! $seen{$_} ++ } @{$Hash{$key}}), "\n";
...
任何建议都将受到高度评价。
【问题讨论】: