Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign two arrays to a hash in Perl?

Tags:

hash

perl

I have lines of code with two large arrays (so can't just write it into a hash) which I want to connect with a hash.

For example, $array1[0] becomes the key and $array2[0] becomes the value and so on to $array1[150],$array2[150].

Any ideas how I do this?

like image 324
Jane Avatar asked Sep 15 '10 08:09

Jane


People also ask

Can we assign array to 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 initialize a hash array in Perl?

#!/usr/bin/perl use Data::Dumper; my %hash = (); my @fields = ('currency_symbol', 'currency_name'); my @array = ('BRL','Real'); @hash{@array} = @fields x @array; The output is: $VAR1 = 'currency_symbol'; $VAR2 = '22'; $VAR3 = 'currency_name'; $VAR4 = undef; There is obviously something wrong.


1 Answers

You can do it in a single assignment:

my %hash; @hash{@array1} = @array2; 

It's a common idiom. From perldoc perldata on slices:

If you're confused about why you use an '@' there on a hash slice instead of a '%', think of it like this. The type of bracket (square or curly) governs whether it's an array or a hash being looked at. On the other hand, the leading symbol ('$' or '@') on the array or hash indicates whether you are getting back a singular value (a scalar) or a plural one (a list).

When I see one of these I see a mental image of a zipper...

like image 160
martin clayton Avatar answered Oct 05 '22 05:10

martin clayton