This [...] only works if undef is not a possible value, and empty arrays are not possible.

It doesn't even handle false values (without a minor change).

The following handles false values (including undef) as well as empty arrays:

sub genIterator { my $array = shift; my $index = 0; # Current index into $array my $child_iter; # Iterator for array at $array[$index] return sub { while (1) { # If we're iterating through descendants of a child, if (defined $child_iter) { # If the there is a descendant we haven't returned, if ( my ($element) = $child->() ) { return $element; } # No more descendants for this child. $child_iter = undef; } # Signal end of iteration if done. return if $index >= @$array; # Return next child if it's not an array ref. my $element = $array->[$index++]; return $element if ref $element ne 'ARRAY'; # Prepare to iterate through descendants of child. $child_iter = genIterator($element); } } } my $iter = genIterator \@nested; say while ($_) = $iter->();

In reply to Re^2: An iterator for (not "iterating") a recursive data structure. by ikegami
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.