in reply to Unique keys for multiple values with a Hash

The idea is to push values into array references in the hash. You have a few other typos I have corrected. The following should run:
use strict; my %hash = (); my ($first, $second); while (<DATA>) { ($first, $second) = split; push (@{$hash{$first}}, $second); # from Perl Cookbook 5.7 } while ((my $key, my $value) = each %hash) { print "the Key is: $key\n"; print join("\n",@$value),"\n\n"; } __END__ 5 25 6 27 5 24 5 23 6 29 6 30 4 22 5 25 6 27 4 22 4 21

Replies are listed 'Best First'.
Re: Re: Unique keys for multiple values with a Hash
by Anonymous Monk on Jan 14, 2003 at 19:18 UTC
    The problem that I'm having is that all the values are being put on the array of values, and I just need the unique values I.E.
    the Key is: 4 22 21 the Key is: 5 25 24 23 the Key is: 6 27 29 30
      Sorry, I missed that the first time (as did some others). Here is a quick fix. Replace the final loop with this:
      while ((my $key, my $value) = each %hash) { print "the Key is: $key\n"; my %seen = (); # Perl Cookbook 4.6 Extracting Unique Elements from a List my @uniq = grep { ! $seen{$_}++ } @$value; print join("\n",@uniq),"\n\n"; }
      Update: I see that Ovid also has a good one-pass solution.