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.
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} .
You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.
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.
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.
Use a hash slice,
my %hash_table;
@hash_table{@keys} = @values;
using map,
my %hash_table = map { $keys[$_] => $values[$_] } 0 .. $#keys;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With