I have a list of items to do something to; and an index that tells me which one to fiddle with next. This index is incremented after each twiddle; and wraps to the start at the end of the list. This is simple to code:
my @items = (1,5,6,3,5,2,4);
my $index = 0;
sub do_next
{
do_something($items[$index]);
$index = ($index+1) % @items;
}
But now we need the ability to vary our list of items --Dave
my @items = (1,5,6,3,5,2,4);
my $index = -1;
sub add_item
{
push @items, @_;
}
sub do_next
{
if (@items)
{
$index = ($index+1) % @items;
do_something($items[$index]);
}
else
{
$index = -1;
}
}
To understand the additional complexity in
do_next, consider the case when: we hit the last item in the list; then add an item; then
do_next() again.
Now the last part: deleting items while maintaining the index. The interesting facts are that the list may have duplicates; and if we delete an item that is earlier in the list than the current index, then we must decrement $index.
Here's the code:
sub remove_item
{
my %del = map {$_=>1} @_;
my @part_1 =
grep { !exists $del{$_} } @items[0..$index];
my @part_2 =
grep { !exists $del{$_} } @items[$index+1..$#items];
$index = $#part_1;
@items = (@part_1, @part_2);
}
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.