Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array in value of hash perl

Is it possible to assign the reference of an array as the value in the key : value pair of a hash table in perl?

like image 351
Daanish Avatar asked Dec 20 '12 04:12

Daanish


People also ask

How do I store an array as a value in hash in Perl?

@values = @{ $hash{"a key"} }; To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value.

Can a Perl hash value be an array?

You can create arrays of hashes, hashes of arrays, and any other sort of complicated data structure you can dream up. To learn more about these, look at the Perl documentation.

Can a hash value be an array?

Hash map is implemented as an array, in which every element includes a list. The lists contain (key, value) pairs. The user can search from the hash map based on the key, and they can also add new key-value pairs into it. Each key can appear at most once in the hash map.

How do I declare an array of hashes in Perl?

A Perl hash is defined by key-value pairs. Perl stores elements of a hash in such an optimal way that you can look up its values based on keys very fast. Like a scalar or an array variable, a hash variable has its own prefix.


1 Answers

Yes it is. Create a reference to the array by using backslash:

$hash{key} = \@array;

Note that this will link to the actual array, so if you perform a change such as:

$array[0] = "foo";

That will also mean that $hash{key}[0] is set to "foo".

If that is not what you want, you may copy the values by using an anonymous array reference [ ... ]:

$hash{key} = [ @array ];

Moreover, you don't have to go through the array in order to do this. You can simply assign directly:

$hash{key} = [ qw(foo bar baz) ];

Read more about making references in perldoc perlref

like image 86
TLP Avatar answered Oct 25 '22 12:10

TLP