Jane Jane - 1 year ago 73
Perl Question

How can I assign two arrays to a hash in 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,

becomes the key and
becomes the value and so on to

Any ideas how I do this?

Answer Source

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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download