http://www.perlmonks.org?node_id=910191


in reply to Dumb, non-question: How to return 'nothing'.

See Higher Order Perl, Chapter 4.5 THE SEMIPREDICATE PROBLEM
# array reference version sub make_iterator { ... return Iterator { my $return_value; ... if (exhausted) { return; } else { return [$return_value]; } } }

Replies are listed 'Best First'.
Re^2: Dumb, non-question: How to return 'nothing'.
by hardburn (Abbot) on Jun 17, 2011 at 20:09 UTC

    That's a nice solution, but is there any particular reason to use an arrayref rather than a scalarref? It'd make the iterating code just a bit cleaner:

    while( my $next = $iter->() ) { $next = $$next; ... }

    As opposed to:

    while( my $next = $iter->() ) { ($next) = @$next; ... }

    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

      I think I've settled on requiring that the iterator be called in a list context. Eg.:

      sub i{ my $n = shift; return sub{ $n ? $n-- : () } };; $i = i( 5 ); print $_ while ( $_ ) = $i->();; 5 4 3 2 1

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        Would be worthwhile to add carp "Iterator not called in list context" unless wantarray; so it can't be used improperly?
      That's a nice solution, but is there any particular reason to use an arrayref rather than a scalarref?

      Its copy/paste from the book, the first solution -- I guess its more generic, re-usability and all that :)

        Seeing as a scalar is always being returned,

        while( my $next = $iter->() ) { ($next) = @$next; ... }

        can be shortened to

        while( my ($next) = @{ $iter->() } ) { ... }