You could use a list assignment in scalar context, and return an empty list to terminate.
sub list_iter { my @list = @_; return sub { return @list ? shift(@list) : (); }; } my $iter = list_iter('a', 1, '', 0, undef, -1); while( my ($next) = $iter->() ) { print( $next // '[undef]', "\n" ); }
Another way is to populate the value using an output parameter.
sub list_iter { my @list = @_; return sub { return 0 if !@list; $_[0] = shift(@list); return 1; }; } my $iter = list_iter('a', 1, '', 0, undef, -1); while( $iter->( my $next ) ) { print( $next // '[undef]', "\n" ); }
In both cases, the output is
a 1 0 [undef] -1
Update: Added second method. Removed some redundant text to "make space" for second method.
In reply to Re: Dumb, non-question: How to return 'nothing'.
by ikegami
in thread Dumb, non-question: How to return 'nothing'.
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |