1. Home
  2. Computing & Technology
  3. Perl

Perl array unshift() function - Quick Tutorial
How to use the array unshift() function

by Kirk Brown
for About.com

$TOTAL = unshift(@ARRAY, VALUES);
Perl's unshift() function is used to add a value or values onto the beginning of an array (prepend), which increases the number of elements. The new values then become the first elements in the array. It returns the new total number of elements in the array. It's easy to confuse this function with push(), which adds elements to the end of an array.
@myNames = ('Curly', 'Moe');
unshift(@myNames, 'Larry');
Picture a row of numbered boxes, going from left to right. The unshift() function would add the new value or values on to the left side of the array, and increase the elements. In the examples, the value of @myNames becomes ('Larry', '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 unshift() function would add the value to the top of the stack, and increase the overall size of the stack.

@myNames = (
'Curly',
'Moe'
);
unshift(@myNames, 'Larry');
You can unshift() multiple values onto the array directly:
@myNames = ('Moe', 'Shemp');
unshift(@myNames, ('Larry', 'Curly'));
Or by unshift()-ing an array:
@myNames = ('Moe', 'Shemp');
@moreNames = ('Larry', 'Curly');
unshift(@myNames, @moreNames);
Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Perl unshift function reference - learn how to use Perl's unshift() function in this quick tutorial.>

©2009 About.com, a part of The New York Times Company.

All rights reserved.