Been there, done that. And found you need a bit more than you've got. ;-)

What you're doing works fine for a maximum of two values for a given key. But you need to check if the value already is an array ref:

if (exists $hash{$key}) { if (ref $hash{$key} and ref $hash{$key} eq 'ARRAY') { push @{$hash{$key}}, $new_val; } else { my @letters_array = $hash{$key}; push @letters_array, $letters; my $new_val = [@letters_array]; $hash{$key} = $new_val; } } else { $hash{$key} = $letters; }
Of course, this becomes a problem if an ARRAY is a legitimate value to be stored in the array, as it is in your example. Now you have to decide what an array means here: does it mean that someone has pre-populated the value with some stuff, and may be adding one or more keys to the list?
my @pushed = (ref $letters && ref $letters eq 'ARRAY') ? @$letters : + $letters; push @{$hash{$key}}, @pushed;
Or is each array ref a legitimate independant value? In this case, it's probably easiest if you treat all keys as always collided. This means that you always use an array. Then you can replace the whole if clause with:
push @{$hash{$key}}, $letters;
And then to check for actual collisions, you can do this:
for $key (keys %found_mod) { if (@{$found_mod{$key}} > 1) { print "This key -- $key -- has more than one value!\n"; } }
As you can see, I've been down this road before. One place you see this type of problem (or at least, one place I've seen it ;-}) is in XML-like hierarchical data where elements can be repeated. For example, XML, HTML, etc.


In reply to Re: Hashes with "duplicate" keys by Tanktalus
in thread Hashes with "duplicate" keys by jacques

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.