Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Removing duplicate values for a hash of arrays

by Eily (Hermit)
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).


Comment on Re: Removing duplicate values for a hash of arrays
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1063772]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2014-09-17 07:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (62 votes), past polls