从 HoA 值中获取唯一元素并打印

时间:2021-03-24 08:00:46

标签: perl hash uniq

我有一个包含特定值的 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::Utiluniq 函数通过以下语句获取唯一元素,我可以获得所需的结果。

use List::Util qw /uniq/;
...
...
print "-Element_$i=", join('#', uniq @{$Hash{$key}}), "\n";
...

因为我的环境中安装了 List::Util1.21 版本,它不支持 List::Util documentation 中的 uniq 功能。

如何在不使用 List::Util 模块的情况下获得所需的结果。

更新/编辑:

我通过在打印语句中添加这一行找到了一个解决方案:

...
print "Element:", join('#', grep { ! $seen{$_} ++ } @{$Hash{$key}}), "\n";
...

任何建议都会受到高度评价。

1 个答案:

答案 0 :(得分:5)

List::Util 有一个纯 Perl 实现。如果您无法更新/安装,我认为这是从另一个模块中提取子模块并将其复制到您的代码中的合法时间之一。

List::Util::PP's implementation of uniq 如下:

sub uniq (@) {
  my %seen;
  my $undef;
  my @uniq = grep defined($_) ? !$seen{$_}++ : !$undef++, @_;
  @uniq;
}
相关问题