Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Basic question about Iterator code

by ikegami (Patriarch)
on May 12, 2025 at 23:15 UTC ( [id://11165019]=note: print w/replies, xml ) Need Help??


in reply to Basic question about Iterator code

As a side note, if you want to support returning false values (such as zero, but particularly undef) easily, return an empty list when the iterator is exhausted.

sub upto { my ( $m, $n ) = @_; return sub { return if $m > $n; return $m++; }; }

or

sub upto { my ( $m, $n ) = @_; return sub { $m <= $n ? $m++ : () }; }

Then, use a list assignment in scalar/boolean context.

my $iter = upto( -2, 2 ); while ( my ( $ele ) = $iter->() ) { say $ele; }
-2 -1 0 1 2

You could have used while ( defined( my $i = $iter->() ). But you won't be able to use that for every iterators, such as one that returns the elements of an array:

sub list { my @a = @_; return sub { @a ? shift( @a ) : () }; } my $iter = list( 1, 0, undef, "a" ); # This doesn't work: # while ( defined( my $ele = $iter->() ) ) { # say $ele // "[undef]"; # } while ( my ( $ele ) = $iter->() ) ) { say $ele // "[undef]"; }
1 0 [undef] a

Since you sometimes need to use the empty-list "trick", you might as well always use it for consistency. Also, it's shorter than using defined :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2025-07-20 18:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.