perl hash slices are a way to access several elements of a hash simultaneously using a list of subscripts. It's more convenient than writing out the individual elements as a list of separate scalar values.

I recently needed to create a slice of a hash rather than a hash slice, ie. I wanted to create a hash with a subset of the key/value pairs from another hash.

Here's how I did it:

my %orginal = (foo => 'something', bar => 42, baz => 'king');
my %subset = map {$_ => $original{$_}} qw(foo bar));
# %subset is now: ( foo => 'something',  bar => 42 )

One thought on “perl: slice of a hash vs hash slice

  1. If you find yourself doing this a lot, I'd suggest using Hash::MoreUtils::slice, as it would clarify your intention more, and you're less likely to make mistakes (like, say, adding an extra paren on the second line).

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 


This site uses Akismet to reduce spam. Learn how your comment data is processed.