G'day rahulme81,

That's a FAQ: How can I remove duplicate elements from a list or array?.

To keep the values unique for a specific key, without removing duplicates from the values of other keys, you'll need to clear the %seen hash for each arrayref value. Here's how you might implement that:

#!/usr/bin/env perl use strict; use warnings; use Data::Dump; my $HASH1 = { 'Alabama' => ['Andalusia', 'Anniston', 'Clanton', 'Eufaula', 'Auburn', + 'Bessemer', 'Eufaula', 'Auburn', 'Bessemer' ], 'California' => ['Barstow','Barstow'], 'Georgia' => ['Darien'], 'New York' => ['Amsterdam','Coney Island','Coney Island','Beacon','Bec +on'] }; for (values %$HASH1) { my %seen; $_ = [ grep { ! $seen{$_}++ } @$_ ]; } dd $HASH1;

Output:

{ "Alabama" => [ "Andalusia", "Anniston", "Clanton", "Eufaula", "Auburn", "Bessemer", ], "California" => ["Barstow"], "Georgia" => ["Darien"], "New York" => ["Amsterdam", "Coney Island", "Beacon", "Becon"], }

Note that the input shown in your OP has the two unique values 'Beacon' and 'Becon', but your expected output only has 'Becon': I suspect a typo. Beyond that, my actual output matches your expected output.

See also: values.

— Ken


In reply to Re: Hash Multiple values for a key-Filtering unique values for a key in hash by kcott
in thread Hash Multiple values for a key-Filtering unique values for a key in hash by rahulme81

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.