Recipe 4.16. Implementing a Circular List (Perl Cookbook)

Perl Cookbook

Perl CookbookSearch this book
Previous: 4.15. Sorting a List by Computable FieldChapter 4
Arrays
Next: 4.17. Randomizing an Array
 

4.16. Implementing a Circular List

Problem

You want to create and manipulate a circular list.

Solution

Use unshift and pop (or push and shift) on a normal array.

Procedure

unshift(@circular, pop(@circular));  # the last shall be first
push(@circular, shift(@circular));   # and vice versa

Discussion

Circular lists are commonly used to repeatedly process things in order; for example, connections to a server. The code shown above isn't a true computer science circular list, with pointers and true circularity. Instead, the operations provide for moving the last element to the first position, and vice versa.

sub grab_and_rotate ( \@ ) {
    my $listref = shift;
    my $element = $listref->[0];
    push(@$listref, shift @$listref);
    return $element;
}

@processes = ( 1, 2, 3, 4, 5 );
while (1) {
    $process = grab_and_rotate(@processes);
    print "Handling process $process\n";
    sleep 1;
}

See Also

The unshift and push functions in perlfunc (1) and Chapter 3 of Programming Perl; Recipe 13.13


Previous: 4.15. Sorting a List by Computable FieldPerl CookbookNext: 4.17. Randomizing an Array
4.15. Sorting a List by Computable FieldBook Index4.17. Randomizing an Array

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.