in reply to How to extract part of a hash
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,
compared to,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);
Benchmarking also shows that slicing is slightly faster than using map.my %order_line = read_from_csv(); my @fields = qw(firstname lastname); my $customer = Customer->find_or_create({ map {$_ => $order_line{$_}} @fields });
#!/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!
|
|---|