in reply to Re: list reversal closure
in thread list reversal closure
Since the loop stop when undefined is returned, the following is the same, but simpler:
sub reverse_iterator { my @list = @_; sub { return pop @list; }; }
Update: I prefer to signal the end of the list out of band to allow undefined values in @list. That why I prefer returning the value through an argument.
sub reverse_iterator { my @list = @_; sub { return unless @list; $_[0] = pop @list; return 1; }; } my $foo = reverse_iterator(@ARGV); while ($foo->(my $val)) { print("$val\n"); }
Update: I just noticed that you assigned to $_ without localizing it first. Don't do that!
Update: s/shift/pop/
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: list reversal closure
by apotheon (Deacon) on Aug 21, 2006 at 19:54 UTC |