Say I have a hash like this:
I'd like to grab just the pets out of this hash, so that I end up with:%hash = ( name => 'Rhesa', fruit => 'Mango', dog => 'Spot', cat => 'Stofje', );
How would you do this?%pets = ( dog => 'Spot', cat => 'Stofje', );
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:
That's just wrong. Unfortunately, I see it quite often in my code base, most notably when creating Class::DBI objects2.%pets = ( dog => $hash{dog}, cat => $hash{cat}, );
Of course, there's the two-stage approach using slices:
But I don't like that it requires a temporary variable.my @animals = qw( dog cat ); my %pets; @pets{ @animals } = @hash{ @animals };
The next best thing I could think of is:
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.%pets = map { $_ => $hash{$_} } qw( dog cat );
I'm gravitating towards writing a function for it:
Is that the best we can do?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 ) );
2
The file has these columns (and more):
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:@headers = qw( firstname lastname address_line1 address_line2 city zip state country order_number title bookcode isbn quantity );
And so on and so forth. It's a pain to read, and maintain.# %orderline comes from the csv my $customer = Customer->find_or_create({ firstname => $orderline{firstname}, lastname => $orderline{lastname}, });
In reply to How to extract part of a hash by rhesa
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |