Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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

by Anonymous Monk
on Jun 17, 2011 at 15:53 UTC ( #910191=note: print w/ replies, xml ) Need Help??


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]; } } }


Comment on Re: Dumb, non-question: How to return 'nothing'.
Download Code
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->() } ) { ... }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://910191]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2014-09-20 02:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (151 votes), past polls