in reply to How to extract part of a hash

First of all, since you actually present some analysis on some alternative ways, I think the proper title would be What's the best way to extract part of hash?. With or without title changing, the essential of your question, at least what read to me, is still to find the best way to do a thing. And, like many questions on the best way to do things in Perl, it really depends on what restrictions to be applied. But, frankly, I still don't understand what your goal is.

For me, slicing is the most straight way to extract partial elements from hash and array. But we do need temporary variable to store the target hash if what we need is partial hash, along with keys and values. Using map allows us to extract partial elements without temporary variables. Consider this,

my %order_line = read_from_csv(); my @fields = qw(firstname lastname); my %identity; @identity{@fields} = @order_line{@fields}; my $customer = Customer->find_or_create(\%identity);
compared to,
my %order_line = read_from_csv(); my @fields = qw(firstname lastname); my $customer = Customer->find_or_create({ map {$_ => $order_line{$_}} @fields });
Benchmarking also shows that slicing is slightly faster than using map.
#!/usr/bin/perl use strict; use warnings; use Benchmark 'cmpthese'; my $count = shift || -1; my %source_hash = ( firstname => 'Perl', lastname => 'Monks', address_line1 => 'http://www.perlmonks.org', address_line2 => 'http://www.perlmonks.com', city => 'cyber', zip => '209.197.123.153', state => 'stable', country => 'Internet', order_number => 'N/A', title => 'not applicable', ); my @partial = qw(firstname lastname); cmpthese $count, { with_slice => sub { my %target_hash; @target_hash{@partial} = @source_hash{@partial}; }, with_map => sub { my %target_hash = map {$_ => $source_hash{$_}} @partial; }, }; # Result: # Rate with_map with_slice # with_map 110277/s -- -28% # with_slice 153325/s 39% --

Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!