Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Removing duplicate values for a hash of arrays

by Eily (Prior)
on Nov 21, 2013 at 18:27 UTC ( #1063772=note: print w/replies, xml ) Need Help??

in reply to Removing duplicate values for a hash of arrays

With a regular hash you just have to do:

%reverseHash = reverse %hash; %hash = reverse %reverseHash;
to eliminate duplicate values. Which of course doesn't work in your case, because the arrays in @hash{'a', 'c'} are no the same, though they contain the same values, and so have different references. Well, you could always turn those arrays into something identical. If you have someFunc(PARAM) that returns the same thing if and only if the values in the data structure PARAM are identical, you can do:
my %reverseHash; while(($key, $value)=each %hash) { $processedValue = someFunc($value); $reverseHash{$processedValue} = $key; } my @keys = values %reverseHash; my %newHash; @newHash{@keys} = @hash{@keys};

The thing is, there is an easy solution for someFunc : Data::Dumper (and this time I'll use map)

use Data::Dumper; my %hash = ( a => [1, 2], b => [2, 3], c => [1, 2] ); my %reverseHash = map { Dumper($hash{$_}) => $_ } keys %hash; %hash = map { $_ => $hash{$_} } values %reverseHash; print Dumper \%hash;

Edit: this works well for nested arrays, even blessed ones. But with hashes, you probably have to activate Data::Dumper's key sorting (It depends of the version of Perl you are using).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1063772]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2018-05-21 19:02 GMT
Find Nodes?
    Voting Booth?