从HoA值中获取唯一元素并打印 [英] Get unique elements from HoA values and print
问题描述
我有一个包含某些值的HoA.
I have a HoA with certain values in it.
我只需要来自HoA的独特元素.
I need to have only unique elements from the 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
函数通过以下语句获取唯一元素,则能够获得所需的结果.
If I use List::Util
's uniq
function to get the unique elements with following statement, I am able to get the desired result.
use List::Util qw /uniq/;
...
...
print "-Element_$i=", join('#', uniq @{$Hash{$key}}), "\n";
...
由于我在我的环境中安装了 List :: Util
的 1.21
版本,因此该版本不支持 uniq
功能 List :: Util文档.
Since I have List::Util
's 1.21
Version installed in my environment, which doesn't support uniq
functionality as per the List::Util documentation.
如何在不使用 List :: Util
模块的情况下获得期望的结果.
How can I get desired result without using List::Util
module.
更新/
我通过在打印语句中添加以下行找到了解决方案:
I found a solution by adding this line in print statement:
...
print "Element:", join('#', grep { ! $seen{$_} ++ } @{$Hash{$key}}), "\n";
...
任何建议都会引起高度重视.
Any suggestion would be highly apricated.
推荐答案
有List :: Util的纯Perl实现.如果您无法更新/安装,我认为这是从其中一个子模块中取出另一个模块并将其复制到您的代码中的合法时机.
There is a pure Perl implementation of List::Util. If you can't update/install, I think this is one of these times where it's legit to lift out a sub from another module and just copy it into your code.
列表::实用工具::PP对 uniq
的实现如下:
List::Util::PP's implementation of uniq
is as follows:
sub uniq (@) {
my %seen;
my $undef;
my @uniq = grep defined($_) ? !$seen{$_}++ : !$undef++, @_;
@uniq;
}
这篇关于从HoA值中获取唯一元素并打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!