#!/usr/bin/perl use strict; use warnings; my $a = [ 1, [ 2, [ 3, [ 4, 5 ] ] ] ]; my $b = [ 1, [ [ 2, 3 ], [ 4, 5 ] ] ]; my $c = [ [ [ [ 1, 2 ], 3 ], 4 ], 5 ]; sameFringe( $a, $a ); sameFringe( $a, $b ); sameFringe( $a, $c ); my $x = [ 1, [ 2, [ 3, [ 4, [ 5, 6 ] ] ] ] ]; my $y = [ 0, [ [ 2, 3 ], [ 4, 5 ] ] ]; my $z = [ 1, [ 2, [ [ 4, 3 ], 5 ] ] ]; sameFringe( $a, $x ); sameFringe( $a, $y ); sameFringe( $a, $z ); sub sameFringe { my $next_el1 = create_iterator(shift); my $next_el2 = create_iterator(shift); my $match = 1; while (1) { my $left = $next_el1->(); my $right = $next_el2->(); no warnings 'uninitialized'; print $left, " ", $right, "\n"; unless ($left eq $right) {$match = 0 ; last} ; last unless defined $left; } $match ? print "the trees match\n": print "the trees don't match\n"; } sub create_iterator { my $ref = shift; my @ref_list; return sub { while (ref $ref eq 'ARRAY') { unshift @ref_list, @$ref; $ref = shift @ref_list; } my $leaf = $ref; $ref = shift @ref_list; return $leaf; } }