我有一个包含某些值的 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";
...
任何建议都将受到高度重视。
最佳答案
List::Util 有一个纯 Perl 实现。如果您无法更新/安装,我认为这是从另一个模块中取出一个子模块并将其复制到您的代码中是合法的。
List::Util::PP's implementation of uniq
如下:
sub uniq (@) {
my %seen;
my $undef;
my @uniq = grep defined($_) ? !$seen{$_}++ : !$undef++, @_;
@uniq;
}
关于perl - 从 HoA 值中获取独特的元素并打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66776916/