[svn:perlfaq] r11281 - perlfaq/trunk
[email protected] Thu, 15 May 2008 07:44:46 -0700 (PDT)
| Newsgroups | perl.cvs.perlfaq |
|---|---|
| Message-ID | <[email protected]> |
Author: comdog
Date: Thu May 15 07:44:44 2008
New Revision: 11281
Modified:
perlfaq/trunk/perlfaq4.pod
Log:
* perlfaq4: How do I handle circular lists?
+ removed the example moving elements around
+ added example using an index and modulus
+ added example using Array::Iterator::Circular
Modified: perlfaq/trunk/perlfaq4.pod
==============================================================================
--- perlfaq/trunk/perlfaq4.pod (original)
+++ perlfaq/trunk/perlfaq4.pod Thu May 15 07:44:44 2008
@@ -1498,13 +1498,21 @@
=head2 How do I handle circular lists?
-Circular lists could be handled in the traditional fashion with linked
-lists, or you could just do something like this with an array:
+(contributed by brian d foy)
+
+If you want to cycle through an array endlessy, you can increment the
+index modulo the number of elements in the array:
- unshift(@array, pop(@array)); # the last shall be first
- push(@array, shift(@array)); # and vice versa
+ my @array = qw( a b c );
+ my $i = 0;
+
+ while( 1 ) {
+ print $array[ $i++ % @array ], "\n";
+ last if $i > 20;
+ }
-You can also use C<Tie::Cycle>:
+You can also use C<Tie::Cycle> to use a scalar that always has the
+next element of the circular array:
use Tie::Cycle;
@@ -1514,6 +1522,19 @@
print $cycle; # 000000
print $cycle; # FFFF00
+The C<Array::Iterator::Circular> creates an iterator object for
+circular arrays:
+
+ use Array::Iterator::Circular;
+
+ my $color_iterator = Array::Iterator::Circular->new(
+ qw(red green blue orange)
+ );
+
+ foreach ( 1 .. 20 ) {
+ print $color_iterator->next, "\n";
+ }
+
=head2 How do I shuffle an array randomly?
If you either have Perl 5.8.0 or later installed, or if you have