I have two hashes, one big and one small. All of the smaller hash's keys show up in the bigger hash, but the values are different. I want to copy the values from the bigger hash to smaller hash.
E.G.:
# I have two hashes like so
%big_hash = (A => '1', B => '2', C => '3', D => '4', E => '5');
%small_hash = (A => '0', B => '0', C => '0');
# I want small_hash to get the values of big_hash like this
%small_hash = (A => '1', B => '2', C => '3');
An obvious answer would be to loop through the keys of the small hash, and copy over the values like this
foreach $key (keys %small_hash) { $small_hash{$key} = $big_hash{$key}; }
Is there a shorter way to do this?
According to my research, copying a hashref is just as simple as using the equals operator: my $hashref_copy = $hashref; But as far as I can tell, all that does is make $hashref_copy a pointer to the original object.
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..
@small_hash{ keys %small_hash } = @big_hash{ keys %small_hash };
Here's a way you could do it:
%small = map { $_, $big{$_} } keys %small;
Altho that's pretty similar to the for loop.
$small{$_} = $big{$_} for keys %small;
map
proof for those that need one:
my %big = (A => '1', B => '2', C => '3', D => '4', E => '5');
my %small = (A => '0', B => '0', C => '0');
%small = map { $_, $big{$_} } keys %small;
print join ', ', %small;
Output:
A, 1, C, 3, B, 2
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