Forgive the easy question, and please tell me if there is no answer. This is not homework by the way.
I am looking for a neat way to slice a hash to get another hash. I know that hashes can be sliced to get arrays, and that arrays can be sliced to get other arrays. What I am looking for is a neat way to get a hash of a subset of fields from a bigger hash.
Eg: To slice an array to get a smaller array is easy:
my @numbers = ( 0..10 ); my @prime_numbers = @numbers[2,3,5,7];
Also you can slice a has to get an array:
my %london = ( 'Area' => 1572, # Sq Km 'Population' => 7_556_900, 'Elevation' => 24, # m 'Time_Zone' => 'GMT', 'Mayor' => 'Boris Johnson', 'Long' => '0.1275°W', 'Lat' => '51.50722°N', ); my @lat_long = @london{'Lat','Long'};
What I am trying to do is to find a neat way to get a subset hash of just the fields I am interested in. It feels like there ought to be a way in the language, but I can't find it, and my google searches are just finding the standard hash to array form of slicing. What I would like to be able to do is something like this:
my @location_fields = qw( Lat Long Elevation ); # Using the %london hash defined above my %london_location = %london{ @location_fields };
Except it does not work. The best I could come up with is:
my %london_location = map {$_=>$london{$_}} @location_fields;
Is there a neater way?
In reply to Slice a hash to get a subset hash. by chrestomanci
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |