in reply to Hash Multiple values for a key-Filtering unique values for a key in hash
I get multipe values for my keys and values appeared more than one
Each hash key only holds one value. In this case, the value is a reference to an anonymous array. So your question really is "How can I remove duplicate elements from a list or array?"
This is a FAQ. You'ld process each anonymous array and remove duplicates, or create a new anonymous array holding unique items and assign that to the value slot of each hash entry.
If you don't want to reassign to the value slot - because, say, the reference is stored elsewhere too, and you don't want that link to be destroyed - you could use splice to edit the anonymous arrays in-place, like this:
$HASH1 = { 'Alabama' => [ 'Andalusia', 'Anniston', 'Clanton', 'Eufaula', 'Auburn', 'Bessemer', 'Eufaula', 'Auburn', 'Bessemer', ], 'California' => ['Barstow','Barstow'], 'Georgia' => ['Darien'], 'New York' => [ 'Amsterdam','Coney Island','Coney Island', 'Becon','Becon', ], }; for my $key ( keys %$HASH1 ) { my $arrayref = $HASH1->{$key}; my %seen; # empty at each iteration $seen{$_}++ for @$arrayref; # process array from the end towards beginning for my $index ( reverse 0 .. $#$arrayref ) { if ( $seen{$arrayref->[$index]} > 1 ) { $seen{$arrayref->[$index]}--; $removed = splice @$arrayref, $index, 1; print "key $key: removed '$removed'\n"; } } } dd $HASH1; __END__ key Alabama: removed 'Bessemer' key Alabama: removed 'Auburn' key Alabama: removed 'Eufaula' key New York: removed 'Becon' key New York: removed 'Coney Island' key California: removed 'Barstow' { "Alabama" => [ "Andalusia", "Anniston", "Clanton", "Eufaula", "Auburn", "Bessemer", ], "California" => ["Barstow"], "Georgia" => ["Darien"], "New York" => ["Amsterdam", "Coney Island", "Becon"], }
Note that in the OP, in the anonymous array for the key New York you have the entries Becon and Beacon which are different - a typo, I guess.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Hash Multiple values for a key-Filtering unique values for a key in hash
by rahulme81 (Sexton) on May 23, 2017 at 08:21 UTC |