Wednesday, April 13, 2011

How to Use push, pop, shift, and unshift to Rotate Arrays in Perl

use strict;
use warnings;

# --- 1. Rotating the Array to the Right (Last to First) ---
my @letters = ('A' .. 'Z');

# Loop 3 times to rotate 3 positions
for (my $i = 1; $i <= 3; $i++) {
    # pop() removes the last element ('Z', then 'Y', etc.)
    # unshift() immediately places that removed element at the beginning of the array
    unshift(@letters, pop(@letters));
}

print "Rotated Right: @letters\n\n";


# --- 2. Rotating the Array to the Left (First to Last) ---
# Reset the array back to the standard alphabet
@letters = ('A' .. 'Z');

# Loop 3 times to rotate 3 positions in the opposite direction
for (my $i = 1; $i <= 3; $i++) {
    # shift() removes the first element ('A', then 'B', etc.)
    # push() immediately places that removed element at the end of the array
    push(@letters, shift(@letters));
}

print "Rotated Left:  @letters\n";

No comments: