I assume you meant "I know that I can get the value for a certain key if it is the only value for that key".

There are two methods to store more than one value per key: The simple one using string concatenation of the different values and a more sophisticated one where you store a link to an array as hash value. Here is how to do it with string concatenation:

$hash{$key}= 'ape:b:cat' #stores the values 'ape','b' and 'cat' into t +he hash using ':' as delimiter #simple but the delimiter better not be in any values (you would have +to escape the delimiter which is messy) @values= split /:/,$hash{$key}; #get the values out of the string # checking for a specific value if ($hash{$key}=~/(^|:)$whatimlookingfor(:|$)/) { print "found it"; } $hash{$key}.= ':' . $anothervalue; #add another value (but if the hash + value was empty you have just added two values, an empty string and +$anothervalue. This is another disadvantage)

The other method uses arrays to store the values. The structure is commonly called HashofArrays (HoA). The syntax is a bit more complicated, but it avoids some disadvantages of the first method

$hash{$key}= ['ape','b','cat']; #stores the values 'ape','b' and 'cat' + into the hash @values= @{$hash{$key}}; #get all the values $value= $hash{$key}->[2]; #get the third value $value= $hash{$key}[2]; #get the third value, short form push @{$hash{$key}}, $anothervalue; #add a value

As you can see the second method should be prefered, but if the syntax of a HashofArrays looks daunting to you or you have other compelling reasons, the first method can be used as well


In reply to Re: get a key for a value revisited by jethro
in thread get a key for a value revisited by marc.garcia

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.