Tuesday, April 29, 2008

Perl - How to merge 2 simple hashes ?

How to merge 2 hashes ? with the use of hash slice:

my %hash1 = ( hello1 => 'world1' , foo1 => 'bar1', hello2 => 'foobar' );
my %hash2 = ( hello2 => 'world2' , foo2 => 'bar2' );
my %hash = %hash1; # %hash contains the same keys/values as hash1
@hash{keys %hash2} = values %hash2; # We merge the content of hash2 with hash


This uses hash slices in order to merge the content of hashes. Slices can also be used to remove duplicates entries in an array:

my @array = qw/hello world foo bar hello/;
my %hash;
@hash{@array} = undef;
my @array = keys(%hash);

No comments: