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.

--MidLifeXis


In reply to Re: An iterator for (not "iterating") a recursive data structure. by MidLifeXis
in thread An iterator for (not "iterating") a recursive data structure. by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.