What about something like (untested, assumption that false, and not undef is a flag for end of data, and that the tree is well-formed (no hashref, for example)):
sub genIterator {
my $tree = shift;
my @stack = ( [ 0, $tree ], 0 );
return sub {
my $work = shift( @stack );
while ( ref( $work ) ) {
my $index = $work->[0];
my $worktree = $work->[1];
if ( $index >= scalar( @{$worktree} ) ) { # Update 3
$work = shift( @stack );
next;
}
elsif ( ! ref( $worktree->[$index] ) ) {
unshift( @stack, [ $index+1, $worktree ] );
return $worktree->[$index];
}
else {
unshift( @stack, [ $index+1, $worktree ] );
$work = [ 0, $worktree->[$index] ];
next;
}
}
return; # empty stack
}
}
Test Code:
my @data = [ [ 0 ], 1, 2, [ 3, 4, 5 ], 6, [ 7, 8, [ 9, 10 ], [ 11, [ 1
+2 ], 13 ], ], 14 ];
my $it = genIterator( \@data );
use DDP;
p @data;
while (defined( my $x = $it->() )) {
say $x;
}
__END__
[
[0] [
[0] [
[0] 0
],
[1] 1,
[2] 2,
[3] [
[0] 3,
[1] 4,
[2] 5
],
[4] 6,
[5] [
[0] 7,
[1] 8,
[2] [
[0] 9,
[1] 10
],
[3] [
[0] 11,
[1] [
[0] 12
],
[2] 13
]
],
[6] 14
]
]
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Update: No longer need to assume that '0' is an invalid element, but the use of the iterator needs to be adjusted.
Update 2: Compared to Eily's solution, mine is iterative (non recursive), while Eily's is recursive.
UPdate 3: changed '>' to '>=' after testing, added test code.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.