How to compare two arrays for equality in Perl?


In Perl, there are two ways to check if two arrays are equal. We can compare two arrays in Perl with the help of "Storable freeze" function or by creating our own custom function. In this tutorial, we will explore both these approaches with the help of examples.

Example 1

Let's first explore the "Storable freeze" code and understand how it works. Consider the code shown below.

use Storable qw/freeze/;
use strict;

$Storable::canonical = 1;

my @countriesOne   = ('India', 'China', 'Russia', 'USA', 'Germany');
my @countriesTwo   = ('India', 'China', 'Russia', 'USA', 'Germany');
my @countriesThree = ('India', 'China', 'Russia', 'USA', 'Spain');

print "countriesOne = countriesTwo\n"
   if (freeze(\@countriesOne) eq freeze(\@countriesTwo));
print "countriesOne = countriesThree\n"
   if (freeze(\@countriesOne) eq freeze(\@countriesThree));
print "countriesOne != countriesThree\n"
   if (freeze(\@countriesOne) ne freeze(\@countriesThree));

In this code, we are using three arrays, out of which only two are similar. Then, inside the print statements, we are using the freeze keyword along with the eq keyword to compare the arrays for equality.

Output

If we run the above code in a terminal, it will produce the following output −

countriesOne = countriesTwo
countriesOne != countriesThree

Example 2

Now, let's consider an example where we will create our own custom function to compare the arrays for equality. Consider the code shown below.

my @countriesOne = ('India', 'China', 'Russia', 'USA', 'Germany');
my @countriesTwo = ('India', 'China', 'Russia', 'USA', 'Germany');
my @countriesThree = ('India', 'China', 'Russia', 'USA', 'Spain');

print "(@countriesOne) and (@countriesTwo) are equal sets.\n" if
isIdentical( \@countriesOne, \@countriesTwo );

print "(@countriesOne) and (@countriesThree) are equal sets.\n" if
isIdentical( \@countriesOne, \@countriesThree );

print "(@countriesTwo) and (@countriesThree) are equal sets.\n" if
isIdentical( \@countriesTwo, \@countriesThree );

sub isIdentical {
   my( $left, $right ) = @_;
   return 0 if scalar @$left != scalar @$right;
   my %hash;
   @hash{ @$left, @$right } = ();
   return scalar keys %hash == scalar @$left;
}

In this code, we are using the "scalar" keyword inside a "sub" to compare two arrays for equality.

Output

If you run this code in a terminal, it will produce the following output −

(India China Russia USA Germany) and (India China Russia USA Germany) are equal sets.

Updated on: 26-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements