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.