in reply to Re^4: Tie::Hash::MultiValue Unique question
in thread Tie::Hash::MultiValue Unique question

Oh! You keep talking about avoiding duplicates in a hash, but your problem is actually with avoiding duplicates in an array.

A common idiom to weed out duplicates is: (from perlfaq4)

my %seen; my @array = grep !$seen{$_}++, LIST;

To insert at the same time, that would be

my %seen; my @array = grep !$seen{$_}++, @array, $new_value;

Plug it in and get:

my %edges; while (<STREAM>) { my($node1, $node2) = split; my %seen; @{$edges{$node1}} = grep !$seen{$_}++, @{$edges{$node1}}, $node2; }

A faster (but more memory hungry) version would be:

my %edges; my %seen; while (<STREAM>) { my($node1, $node2) = split; next if !$seen{$node1}{$node2}++; push @{$edges{$node1}}, $node2; }

Replies are listed 'Best First'.
Re^6: Tie::Hash::MultiValue Unique question
by elsubliminal (Initiate) on Apr 18, 2009 at 07:15 UTC
    Ahh Yes! Thanks for someone still making sense out of my
    pitifully worded question!
    The point is that I want to avoid duplicates in values, not keys.
    When googled this bit, I found out I could use Tie::Hash::Multivalue
    for ensuring I can add multiple values
    to a key in the hash, and I can pass an argument
    'Unique' to ensure that only unique values get added.
    So that was my original question - how do I pass the argument
    "unique" to Tie::Hash::Multivalue?

    Thanks all for responding!
      # Uses string compare to determine uniqueness. tie %hash, 'Tie::Hash::MultiValue', 'unique'; # Uses numerical compare to determine uniqueness. tie %hash, 'Tie::Hash::MultiValue', unique => sub { $_[0] == $_[1] };
        Thanks Much!