Monday, March 9, 2009

How to Take a Hash Slice

Assign some variables of a hash to an array. i.e you want to take some of the elements from hash based on there keys into a array here is a trick

%hash = ( 1 => 'one', 2 => 'two',3 => 'three');
@array = @hash{'1','2'};



If you have a hashref and want to take the values of some keys into an array you can do the following.

$hashref = {1 => 'one', 2 => 'two', 3 => 'three'};
@array = @{%$hashref}{'1','2'};


No comments: