jshakil
jshakil

Reputation: 97

Moving and Altering First/Last Elements of Array in Perl

I have an array containing the following words:

@animals = (
    "cat",
    "dog",
    "mouse",
    "elephant",
    "giraffe"
);

How would I move element 0 to the end of the array? So now it will become:

@animals = (
    "dog",
    "mouse",
    "elephant",
    "giraffe",
    "cat"
);

Is there a simple way using shift, unshift, pop, or push?

Upvotes: 1

Views: 1130

Answers (1)

Schwern
Schwern

Reputation: 164829

  • shift removes the first element.
  • unshift adds an element to the front.
  • pop removes the last element.
  • push adds an element to the end.
  • splice can add and remove any number of elements from anywhere in the list.

shift/unshift work at the front, pop/push work at the end.

In your case, you want push(@animals, shift(@animals)). Remove the first element and put it on the end.

Upvotes: 4

Related Questions