Broad Network


Combining Perl Hashes

Using Perl Hashes Part 3

Perl Course

Foreword: In this part of the series, I explain how to get the unique keys from two hashes and how to merge two hashes.

By: Chrysanthus Date Published: 3 Nov 2015

Introduction

This is part 3 of my series, Using Perl Hashes. In this part of the series, I explain how to get the unique keys from two hashes and how to merge two hashes. You should have read the previous parts of the series before coming here, as this is a continuation.

Obtaining Unique Keys from two Hashes
In a hash, the keys are always unique. However, it is possible to have two hashes where some of the keys are the same; the corresponding values may or may not be the same. Assume that the two hashes are:

    my %hash1 = (one=>'aa', two=>'bb', three=>'cc');

and

    my %hash2 = (two=>'bb', three=>'cc', four=>'dd');

To copy the unique keys into an array, say @unique, you would type:

    my @unique = keys %{{%hash1, %hash2 }};

This statement needs explanation: Now,

    {%hash1, %hash2 }

is a hash by reference (returning a reference) that is temporary equivalent to,

    {one=>'aa', two=>'bb', three=>'cc', two=>'bb', three=>'cc', four=>'dd'}

A hash will never allow duplicate keys, so the duplicate keys go off resulting in,

    {one=>'aa', two=>'bb', three=>'cc', four=>'dd'}

which is a proper hash by reference. Assume that you have a reference to a hash that is $href. To dereference this, you would type, %{$href } . The proper hash is returning a reference, so to dereference it, you would have:

    %{{one=>'aa', two=>'bb', three=>'cc', four=>'dd'}}

This is now a normal hash where duplicate keys have been removed. The keys() function having this expression as the argument, returns the list of keys, which can be assigned to an array variable. Try the following code:

use strict;

    my %hash1 = (one=>'aa', two=>'bb', three=>'cc');

    my %hash2 = (two=>'bb', three=>'cc', four=>'dd');

    my @unique = keys %{{%hash1, %hash2 }};

    print "$_ " foreach @unique;

In my computer, the output was,

    three four one two

The order was not respected. This is because the order in hashes are not respected.

Merging two Hashes
It is not difficult to merge two hashes. You can just use the scalar expression, $hash2{key2} to assign the key/value pairs of hash2 to hash1, iterating as in:

    $hash1{key2} = $hash2{key2}

In the assignment operation, the copies are made (hash2 elements are created and added into hash1). You end up with a larger hash1. Well, there is a problem: duplicate keys in hash2 will override their counterparts in hash1. To copy duplicate keys and their values from hash2, just rename the duplicate keys, by appending say 2 to the keys. It is also good to leave hash1 and hash2 alone and have a new hash that has all the keys plus the duplicate keys renamed.

And so, to merge two hashes, copy hash1 to the new hash. As you are copying hash2 to the new hash, you are checking if there is duplicate. If there is duplicate, you rename the key, and you copy. Read and try the following code:

use strict;

    my %hash1 = (one=>'aa', two=>'bb', three=>'cc');

    my %hash2 = (two=>'bb', three=>'cc', four=>'dd');


    my %newHash = %hash1;

    foreach my $key2 ( keys %hash2 )
        {
            if(exists $newHash{$key2})  
                {
                    $key2 = $key2 . '2';
                    $newHash{$key2} = $hash2{$key2};
                }
        else
            {
                $newHash{$key2} = $hash2{$key2};
            }
        }

    print "$_ " foreach %newHash;

In my computer, the output was,

    two2 bb three2 cc two bb four dd one aa three cc

with the duplicated key elements maintained. The order was not maintained because hashes do not maintain order. In the code, the assignment operation that does the copying, copies and creates the element (key/value pair) at the same time.

That is it for this part of the series. We stop here and continue in the next part.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message