Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying values from one hash to another in perl

Tags:

hash

perl

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?

like image 202
Ron Avatar asked Jun 13 '12 14:06

Ron


People also ask

How do I copy a hash in Perl?

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.

How does Perl store data in hash?

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..


2 Answers

@small_hash{ keys %small_hash } = @big_hash{ keys %small_hash };
like image 108
Chris Charley Avatar answered Oct 06 '22 23:10

Chris Charley


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
like image 23
Qtax Avatar answered Oct 07 '22 00:10

Qtax