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 :)