1. Technology

Perl array shift() function - Quick Tutorial

How to use the array shift() function

By

Man working on laptop computer
Manabu Ogasawara/Stockbyte/Getty Images
 $ITEM = shift(@ARRAY); 
Perl's shift() function is used to remove and return the first element from an array, which reduces the number of elements by one. The first element in the array is the one with the lowest index. It's easy to confuse this function with pop(), which removes the last element from an array.
 @myNames = ('Larry', 'Curly', 'Moe');
 $oneName = shift(@myNames); 
If you think of an array as a row of numbered boxes, going from left to right, it would be the element on the far left. The shift() function would cut the element off the left side of the array, return it, and reduce the elements by one. In the examples, the value of $oneName becomes 'Larry', the first element, and @myNames is shortened to ('Curly', 'Moe').

The array can also be thought of as a stack - picture of a stack of numbered boxes, starting with 0 on the top and increasing as it goes down. The shift() function would shift the element off the top of the stack, return it, and reduce the size of the stack by one.

 @myNames = (
 'Larry',
 'Curly',
 'Moe'
 );
 $oneName = shift(@myNames); 
  1. About.com
  2. Technology
  3. Perl
  4. Programming Perl
  5. Perl Array Shift() Function - Quick Tutorial

©2014 About.com. All rights reserved.