Rotate one to the left

Last week I wrote a small function in Perl that rotates and array to left. The function takes the item from the front and appends it to the back.

# precondition: @list >= 1;
sub rotate_left_by_one {
    my $ar = shift;
    my $item = shift @$ar;
    push @$ar, $item;

After calling this function as many times as the length of the array, it leaves the items in the same order they started in. Every call to this function puts a different item in the first location. I use it to compare this item to the rest of the items.

You would use it like this:

while (1 .. @list) {
    # your code

This function works great when the code doesn't depend on the order of the items in @list. The items in @list will be in a different order than what it started with for most of the iterations of the loop. This means that the code in the loop body needs to have the commutative property.


My name is Peter Stuifzand. You're reading my personal website.