Shift and Unshift Functions in Perl
What is Shift, Unshift Function?
How to add / remove an element from the beginning of an array?
Explanation
Add Elements to an Array:
Unshift Function:
Unshift is used to add an element to the begining of an array.
Syntax:
unshift ARRAY, LIST;
In the above syntax the "ARRAY" specifies the array to which the elements in "LIST" are to be added in the begining.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
@color = ("red", "blue");
unshift (@color, "green");
$,="n";
print @color;
Result
green red blue
The array @color will have three elements with "green" as the first element.
Remove Elements from an Array:
Shift Function:
Shift is used to remove an element from the begining of an array.
Syntax:
shift (ARRAY);
In the above syntax "ARRAY" specifies the array from which an element need to be removed from the begining.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
@color = ("red", "blue", "green");
shift (@color);
$,="n";
print "@color";
Result :
blue green
In the above example, the first element "red" is removed from the begining of an array, then the rest of the array is displayed.