Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Convert array of keys and values into a hash

Tags:

arrays

hash

perl

I have two arrays like this

my @keys = qw/Key_1 Key_2 Key_3/;
my @values = qw/foo bar more/;

Is there a short way (i.e. a single function) to get a hash like this without using a loop?

my %hash_table = ( Key_1 => "foo", Key_2 => "bar", Key_3 => "more" );

I tried to use map function but no success.

like image 921
Wernfried Domscheit Avatar asked Jun 03 '14 09:06

Wernfried Domscheit


People also ask

How do I assign an array value to a hash in Perl?

To assign that array to a hash element, you'd use either $b{"x"} = [@a] or $b{"x"} = \@a , depending on what you're trying to do. [@a] makes a new arrayref containing a copy of the current contents of @a . If the contents of @a change after that, it has no effect on $b{x} .

How do I merge two arrays into a hash in Perl?

You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.

How do I push data into a hash in Perl?

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. When inverted, you end up with a hash that has many values for the same key.

Can you hash an array?

Python Hashing (Hash tables and hashlib) While an array can be used to construct hash tables, array indexes its elements using integers. However, if we want to store data and use keys other than integer, such as 'string', we may want to use dictionary. Dictionaries in Python are implemented using hash tables.


1 Answers

Use a hash slice,

my %hash_table;
@hash_table{@keys} = @values;

using map,

my %hash_table = map { $keys[$_] => $values[$_] } 0 .. $#keys;
like image 146
mpapec Avatar answered Sep 27 '22 23:09

mpapec