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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.