What is array.shift() in Perl?

Overview

The shift() method in Perl is used to return the first value of an array. It removes the first element and shifts the array list elements to the left by one.

Syntax

shift(@arr)

Parameters

@arr: This is the array whose elements we want to shift.

Return value

It returns the first element of the array after removing it from the array. However, if the array is empty, it returns -1.

Code example

# create an array
@arr = ("e", "a", "b", "c", "d");
# print array values
print "Before shift: @arr \n";
# shift element
@shifted_element = shift(@arr);
# print shifted element
print "Shifted Element: @shifted_element";
# print array values
print "\nAfter shift: @arr";

Explanation

  • Line 2: We create an array called arr.
  • Line 5: We print the values of arr to the console.
  • Line 8: We shift the first element of the array we created with the shift() method.
  • Line 11: We print the shifted element.
  • Line 14: We print the he new values of the array after the shift to the console.