Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
shift
perl
communitycreator

What is array.shift() in Perl?

okwudili onyejiaku

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";
Shifting an element from an array in Perl

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.

RELATED TAGS

array
shift
perl
communitycreator
RELATED COURSES

View all Courses

Keep Exploring