How do I extract part of a hash -- as a hash? I (obviously) know about slices, but that only gives you certain values, and I would like to have some key/value pairs1.

Say I have a hash like this:

%hash = ( name => 'Rhesa', fruit => 'Mango', dog => 'Spot', cat => 'Stofje', );
I'd like to grab just the pets out of this hash, so that I end up with:
%pets = ( dog => 'Spot', cat => 'Stofje', );
How would you do this?

1 It occurred to me that the syntax %hash{@keys} would have been ideal for this: it mirrors normal slicing, but instead of a list, it indicates we get a hash back. I realise it's a bit late in the life of perl5 to make this into a serious proposal, but it might have been nice.

The most obvious answer would be:

%pets = ( dog => $hash{dog}, cat => $hash{cat}, );
That's just wrong. Unfortunately, I see it quite often in my code base, most notably when creating Class::DBI objects2.

Of course, there's the two-stage approach using slices:

my @animals = qw( dog cat ); my %pets; @pets{ @animals } = @hash{ @animals };
But I don't like that it requires a temporary variable.

The next best thing I could think of is:

%pets = map { $_ => $hash{$_} } qw( dog cat );
But that shows too much machinery for my taste. It's like having to start your car with a crank instead of a key or button.

I'm gravitating towards writing a function for it:

sub hash_slice { my ($hr, @k) = @_; return map { $_ => $hr->{$_} } @k; } # or using a slice (might be more efficient, but doesn't read as nicel +y) sub hash_slice { my ($hr, @k) = @_; my %ret; @ret{@k} = @$hr{@k}; return %ret; } # use like this: %pets = hash_slice( \%hash, qw( dog cat ) );
Is that the best we can do?

2

I'm importing data from a csv file into a database. The csv file is highly denormalized, while the database is structured nicely. My csv parser returns a hash for each line of data, so I need to store parts of this hash into different tables.

The file has these columns (and more):

@headers = qw( firstname lastname address_line1 address_line2 city zip state country order_number title bookcode isbn quantity );
I need to store this data using Class::DBI classes like Customer, Address, Title, Edition, Order, Orderline etc. So some of these calls look like:
# %orderline comes from the csv my $customer = Customer->find_or_create({ firstname => $orderline{firstname}, lastname => $orderline{lastname}, });
And so on and so forth. It's a pain to read, and maintain.

In reply to How to extract part of a hash by rhesa

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.