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/
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.