Wednesday, November 18, 2009

How to initialize a hash from a list in Perl

Given the following code:


@mylist = qw( little tech tips );



We want to construct a hash with the elements in @mylist as the keys. We can use the x (that's lowercase x) operator for this. Let's say we will initialize the values to cool.

The code will look like this:



@myhash{ @mylist } = "cool" x scalar(@mylist);



One thing to note. The call to scalar is actually not necessary since you're using @mylist in a scalar context with the x operator. But doing it this way makes it clear and less error prone.

No comments: