[ACCEPTED]-map for hashes in Perl-higher-order-functions
List::Pairwise claims to implement exactly that syntax 4 -- see mapp
, grepp
. I haven't used it though.
Also, you 3 can do it as
%new_hash = map { new_key($_) => new_value($hash{$_}) } keys %hash;
which I admit looks clumsier 2 if %hash
is really a $deeply->{buried}->{hash}
. I prefer using $temp = ...; map {...} keys %$temp
in such 1 cases.
I really can’t see what you are trying to 13 do here. What does “a hash equivalent for 12 map
” even mean? You can use map
on a hash just 11 fine. If you want the keys, just use keys
; for 10 example"
@msglist = map { "value of $_ is $hash{$_}" } keys %hash
although usually
say "value of $_ is $hash{$_}" keys %hash;
is just fine.
If 9 you want both, then use the whole hash.
For 8 assignment, what’s wrong with %new_hash = %old_hash
?
Do you have 7 deep-copy issues? Then use Storable::dclone
.
Do you want 6 both key and value available in the closure 5 at the same time? Then make a bunch of pairs 4 with the first map:
@pairlist = map { [ $_ => $hash{$_} ] } keys %hash
I need to see an example 3 of what you would want to do with this, but 2 so far I can see zero cause for using some 1 big old module instead of basic Perl.
You can use map like this:
my $i = 0;
my %new_hash = map { $i ^= 1 ? new_key($_) : new_val($_) } %hash;
0
You can use mapn
from my module List::Gen to do this:
use List::Gen 'mapn';
my %new_hash = mapn {new_key($_[0]) => new_value($_[1])} 2 => %old_hash;
mapn
is 4 like map, except it it takes an additional 3 argument, the number of elements to walk 2 the list by. Inside the block, the @_
array 1 is set to the current slice.
$ perl -d /dev/null
DB<2> %p = ( a=>'b', c=> 'd');
DB<5> p Dumper \%p
$VAR1 = {
'c' => 'd',
'a' => 'b'
};
To e.g. reverse the key 1 and the value:
DB<6> %q = map { ($p{$_}, $_ ) } keys %p
DB<7> p Dumper \%q
$VAR1 = {
'b' => 'a',
'd' => 'c'
};
List::Util::pairmap
in core does exactly that:
use List::Util qw(pairmap);
my %new_hash = pairmap { new_key($a) => new_val($b) } %hash;
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.