Rate this page

Recursively compare the content of two arbitrary Perl data structures

Tested on

Debian (Etch, Lenny, Squeeze)
Fedora (14)
Ubuntu (Hardy, Intrepid, Jaunty, Karmic, Lucid, Maverick, Natty, Trusty)


To recursively compare the content of two arbitrary Perl data structures


Suppose you are writing a test harness for a Perl function called get_credentials which returns a hash ref. You know exactly what value it should return and wish to test whether it has done so.


You can compare Perl data structures using the Data::Compare module. First the module must be installed. On Debian-based systems it is located in the package libdata-compare-perl:

apt-get install libdata-compare-perl

The next step is to load the module. The function that you are most likely to need, called Compare, is imported by default:

use Data::Compare;

You should now be able to compare any two data structures by passing them to the Compare function:

my $returned_data = get_credentials;
my $expected_data = {username=>'user',password=>'xyzzy'};
if (!Compare($returned_data,$expected_data)) {
	die 'unexpected response from get_credentials';

The value returned by Compare is 1 if the values match or 0 if they do not.

Tags: perl