I have a HoA with certain values in it.
I need to have only unique elements from the HoA.
Expected Result:
Key:1
Element:ABC#DEF
Key:2
Element:XYZ#RST
Key:3
Element:LMN
Below is my script:
#!/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 } @_ } };
The script throws me following error:
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.
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";
...
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.
How can I get desired result without using List::Util module.
Update/Edit:
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.
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.
List::Util::PP's implementation of uniq is as follows:
sub uniq (@) {
my %seen;
my $undef;
my @uniq = grep defined($_) ? !$seen{$_}++ : !$undef++, @_;
@uniq;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With