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

vin*_*k89 3 perl hash uniq

我有一个带有某些值的 HoA。

我只需要来自 HoA 的独特元素。

预期结果:

Key:1
Element:ABC#DEF
Key:2
Element:XYZ#RST
Key:3
Element:LMN
Run Code Online (Sandbox Code Playgroud)

下面是我的脚本:

#!/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 } @_ } };
Run Code Online (Sandbox Code Playgroud)

该脚本向我抛出以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

如果我使用List::Util'suniq函数通过以下语句获取唯一元素,则可以获得所需的结果。

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

因为我List::Util1.21安装在我的环境,不支持版本uniq的功能按照清单::的Util文件

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

更新/编辑:

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

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

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

sim*_*que 5

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

List::Util::PP 的实现uniq如下:

sub uniq (@) {
  my %seen;
  my $undef;
  my @uniq = grep defined($_) ? !$seen{$_}++ : !$undef++, @_;
  @uniq;
}
Run Code Online (Sandbox Code Playgroud)