NOTE that this example iterates over HoH not AoAs (which is a bit silly b/c order matters) since I have only 5.10 installed.
With >=5.12 each should also work with ARRAYs! (testing appreciated)
It might not be the most elegant solution but
a) it's really lazy - not only for the programmer - and
b) it can iterate nested Arrays and Hashes alike for >=5.12.
c) it's quite fast.
d) I can tell the recursion "depth" of each iteration. NOTE I'm only returning 3 values for better visualization/debugging. Only $v matters for this task.
use Data::Dump 'dd'; use strict; use warnings; dd my $h1 = { a => {b => {c => 1}, d=> 2}, e=>3,f=>4 }; dd my $h2 = { a => {b => {c => 1}, d=> 2}, e=>3,f=>4 }; sub gen { my $ref=shift; my @path=(); return sub { while (1) { while (my ($k,$v) = each %$ref) { if ( ref $v eq "HASH") { push @path,$ref; $ref =$v; next; } else { return $k,$v,scalar @path; } } return unless $ref = pop @path; } } } my $iter1=gen($h1); my $iter2=gen($h2); while ((my ($k1,$v1,$l1) = $iter1->()) + (my ($k2,$v2,$l2) = $iter2->( +)) ) { die "error $v1 != $v2" if $v1 ne $v2; print "$l1: $k1=> $v1\n"; }
a more functional solution on Monday./usr/bin/perl -w /tmp/lanx_fringe.pl { a => { b => { c => 1 }, d => 2 }, e => 3, f => 4 } { a => { b => { c => 1 }, d => 2 }, e => 3, f => 4 } 0: e=> 3 2: c=> 1 1: d=> 2 0: f=> 4
Cheers Rolf
( addicted to the Perl Programming Language)
I just realized that it's about binary trees and that the representation of them is free.
So when choosing nested hashes with keys L and R , this algorithm already delivers the needed features. =)
Limitations see Re^3: Challenge: Perl 5: lazy sameFringe()?
In reply to Re: Challenge: Perl 5: lazy sameFringe()?
by LanX
in thread Challenge: Perl 5: lazy sameFringe()?
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |