Re: hash of arrays question



Skeleton Man wrote:

I'm new to perl and have a question. The perl book
says that hashes map keys to values. Using the reverse
function you can map values to keys. My problem is
I have a hash of arrays and I want to map an array
of values to a particular key. Is there any way to
do this?

There are two ways to do this:

$sample{'key1'} = ['item1', 'item2', 'item3']; # Array of values mapped to
a single hash key (note the use of square brackets [])
print $sample{'key1'}[0]; # Prints "item1"

Or:

@data = ('item4, 'item5', 'item6', 'item7'); # Create a new array
$sample{'key2'} = \@data; # Take a reference to the
array (backslash operator), you could use any existing array here too.
print $sample{'key2'};


Let me know if you need anything explained a little more clearly :-)

This means: hash values can be references.

--
mzi
.



Relevant Pages

  • Re: HOA redundancy in array.
    ... creates a new hash called $saw. ... corresponding to the given keys. ... [Given that @HOH_protein is an array, therefore $pro_name is a number, ... for my $got (@uniqs) { ...
    (comp.lang.perl.misc)
  • Re: populating a hash with % used as the key and F string as the value
    ... > keys %lookup; ... it states one cannot push or pop a hash on page 10 ... itself is the reference to the array (read: an arrayref). ...
    (perl.beginners)
  • Re: maintaining order in a hash (without Tie::IxHash)
    ... Save the keys in a separate array and iterate over the array. ... >> is the simplest approach at the expense of duplicate storage of the ... accessing a large hash by sorting a ...
    (comp.lang.perl.misc)
  • Re: Traversing a hash with array refs as keys?
    ... Hash keys can only be strings. ... So is your key an array or an array reference? ... As mentioned above keys must be strings. ...
    (comp.lang.perl.misc)
  • Re: sorting and resorting hash
    ... There's no reason to be adding values to an array if you're only using ... Just build the hash directly. ... of the entire %rms hash each time through the loop. ... Why are you creating a whole new array to just store the keys of the hash ...
    (comp.lang.perl.misc)