|
Posted by John W. Krahn on May 13, 2008, 9:11 am
Please log in for more thread options sheinrich@my-deja.com wrote:
>> --------------------------------------------------------------------
>>
>> 4.47: How do I handle circular lists?
>>
>> Circular lists could be handled in the traditional fashion with li=
nked
>> lists, or you could just do something like this with an array:
>>
>> unshift(@array, pop(@array)); # the last shall be first
>> push(@array, shift(@array)); # and vice versa
>>
>>
>=20
> As the modulo operator provides a simple way to address an array in a
> circular fashion, which is maybe not obvious to the less experienced,
> I think it should be mentioned here.
>=20
> my @Colours =3D qw( FFFFFF 000000 FFFF00 );
>=20
> my $asize =3D @Colours;
> my $index =3D 0;
>=20
> for (1..10) {
> print $Colours[$index], "\n";
>=20
> $index =3D ++$index % $asize;
perldoc perlop
[ SNIP ]
Note that just as in C, Perl doesn=92t define when the variable is
incremented or decremented. You just know it will be done sometime
before or after the value is returned. This also means that
modifying a variable twice in the same statement will lead to
undefined behaviour. Avoid statements like:
$i =3D $i ++;
print ++ $i + $i ++;
Perl will not guarantee what the result of the above statements is.
So don't do that. Do this instead:
$index =3D ( $index + 1 ) % $asize;
John
--=20
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
|