Is there a hash equivalent for map
?
my %new_hash = hash_map { new_key($a) => new_val($b) } %hash;
I know that I could loop through the keys.
Perl for Beginners: Learn A to Z of Perl Scripting Hands-on A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..
Introduction to Perl hashA Perl hash is defined by key-value pairs. Perl stores elements of a hash in such an optimal way that you can look up its values based on keys very fast. With the array, you use indices to access its elements. However, you must use descriptive keys to access hash's element.
List::Pairwise claims to implement exactly that syntax -- see mapp
, grepp
. I haven't used it though.
Also, you can do it as
%new_hash = map { new_key($_) => new_value($hash{$_}) } keys %hash;
which I admit looks clumsier if %hash
is really a $deeply->{buried}->{hash}
. I prefer using $temp = ...; map {...} keys %$temp
in such cases.
I really can’t see what you are trying to do here. What does “a hash equivalent for map
” even mean? You can use map
on a hash just fine. If you want the keys, just use keys
; for example"
@msglist = map { "value of $_ is $hash{$_}" } keys %hash
although usually
say "value of $_ is $hash{$_}" keys %hash;
is just fine.
If you want both, then use the whole hash.
For assignment, what’s wrong with %new_hash = %old_hash
?
Do you have deep-copy issues? Then use Storable::dclone
.
Do you want both key and value available in the closure at the same time? Then make a bunch of pairs with the first map:
@pairlist = map { [ $_ => $hash{$_} ] } keys %hash
I need to see an example of what you would want to do with this, but so far I can see zero cause for using some big old module instead of basic Perl.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With