Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how do I create a hash whose keys come from a given array?

Tags:

arrays

hash

perl

Let's say I have an array, and I know I'm going to be doing a lot of "Does the array contain X?" checks. The efficient way to do this is to turn that array into a hash, where the keys are the array's elements, and then you can just say

if($hash{X}) { ... }

Is there an easy way to do this array-to-hash conversion? Ideally, it should be versatile enough to take an anonymous array and return an anonymous hash.

like image 793
raldi Avatar asked Sep 18 '08 19:09

raldi


People also ask

How do I pass an array to a hash in Perl?

use strict; use Data::Dumper; my @array= qw(foo 42 bar); my %hash; @{ $hash{key} } = @array; $hash{key} = [ @array ]; #same as above line print Dumper(\%hash,$hash{key}[1]);

How do I create a hash in Perl?

Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..

How do I reference a hash in Perl?

Similar to the array, Perl hash can also be referenced by placing the '\' character in front of the hash. The general form of referencing a hash is shown below. %author = ( 'name' => "Harsha", 'designation' => "Manager" ); $hash_ref = \%author; This can be de-referenced to access the values as shown below.

How do I create a hash from two arrays in Perl?

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


2 Answers

%hash = map { $_ => 1 } @array; 

It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.

What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.

like image 169
9 revs Avatar answered Sep 16 '22 14:09

9 revs


 @hash{@array} = (1) x @array; 

It's a hash slice, a list of values from the hash, so it gets the list-y @ in front.

From the docs:

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

like image 38
moritz Avatar answered Sep 20 '22 14:09

moritz