Wednesday 6 October 2010

Merging hashes with Perl - easy but (maybe) tricky

Merging hashes with Perl is extremely easy: you can just "list" them.
For example try this:

use strict;
use warnings;

use Data::Dumper;

my %hash1 = ('car' => 'FIAT', 'phone' => 'Nokia');
my %hash2 = ('laptop' => 'Dell', 'provider' => 'Orange');

my %mergedHash = (%hash1, %hash2);

print "hash1: " . Dumper(\%hash1);
print "hash2: " . Dumper(\%hash2);
print "merged hash: " . Dumper(\%mergedHash);
You'll see that %mergedHash contains the result of merging the two hashes.

This is the simplest but not most efficient way to do it: here Perl Cookbook presents a different method, which uses less memory - interesting if you're merging big hashes (and have memory constraints).

Now the tricky bit is that you can have this merge even when maybe you don't expect it...
For example add this code to the previous lines:

useHashes(%hash1, %hash2);

sub useHashes {
my(%hashInput1, %hashInput2) = @_;
print "hashInput1: " . Dumper(\%hashInput1);
print "hashInput2: " . Dumper(\%hashInput2);
}

What would you expect? Try it out.

What actually happens is that the two hashes are merged inside the call to useHashes(), and all works as if useHashes() received a single argument (the merged hash), instead of two separate arguments (the two original hashes).

No comments:

Post a Comment

Wireshark setting to interpret UDP as RTP automatically

 Before I forget again, a Wireshark setting that can help saving time by trying to interpret any UDP as RTP, if possible: Analyze --> Ena...