in reply to compare two reference in perlway
Hello k_manimuthu,
Combining your recursive approach with the Test::Deep::eq_deeply function suggested by Eily’s post, I came up with the following:
#! perl use strict; use warnings; use Test::Deep::NoTest; my $x = { c => {}, func => [], }; my $x1 = { func => [], c => {}, }; my $x2 = { func => [], c => { s => 't' }, }; my $main = { a => { b => { c => {}, ### equals to $part hash reference func => [], }, func => [ 'd', 'e', ], }, }; printf "%s found\n", walk($main, $x ) ? 'Match' : 'No match'; printf "%s found\n", walk($x, $x1) ? 'Match' : 'No match'; printf "%s found\n", walk($main, $x2) ? 'Match' : 'No match'; sub walk { my ($whole, $part) = @_; my $ref = ref $whole; return 1 if eq_deeply($whole, $part); if ($ref eq 'ARRAY') { for (@$whole) { if (eq_deeply($_, $part)) { return 1; } else { return 1 if walk($_, $part); } } } elsif ($ref eq 'HASH') { for (keys %$whole) { if (eq_deeply($whole->{$_}, $part)) { return 1; } else { return 1 if walk($whole->{$_}, $part); } } } return 0; }
Output:
0:08 >perl 1414_SoPW.pl Match found Match found No match found 0:08 >
The results shown are as expected; however... (disclaimer) a lot more, and more rigorous, testing is still required!
Anyway, hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: compare two references in the Perl way
by k_manimuthu (Monk) on Oct 20, 2015 at 12:57 UTC |