Lesson 15: Array Functions


Common array functions

function description
pop @array removes the last element from an array and returns it
push (@array, new_element(s)) appends one or more elements to an array
shift @array removes the first element of an array, and returns it
unshift (@array, new_element(s)) prepend more elements to the beginning of a list
splice adds or removes elements anywhere in an array
join (character(s),@array) joins the element of the list on a one or more characters and returns a string

pop, push, shift, unshift, and splice change the array.

pop

  • Removes and returns the last element of the array
1
2
3
4
5
6
7
my @array = (3 , 'red' , 'cornflower blue' , 1.2);
print join ('--',@array) , "\n";
 
my $last = pop @array;
 
print "this was the last element: ", $last, "\n";
print join ('--',@array) , "\n";

Output:

%% ./array_functions.pl
3--red--cornflower blue--1.2
this was the last element: 1.2
3--red--cornflower blue

push

  • Adds an element or a list to the end of an array
1
2
3
4
5
my @array = (3 , 'red' , 'cornflower blue' , 1.2);
print "original array: " , join ('--',@array) , "\n";
 
push (@array, 'yellow');
print "current array:  " , join ('--',@array) , "\n";

Output:

%% ./array_functions.pl
original array: 3--red--cornflower blue--1.2
current array:  3--red--cornflower blue--1.2--yellow

shift

  • Removes and returns an element from the front of the array
1
2
3
4
5
6
7
my @array = (3 , 'red' , 'cornflower blue' , 1.2);
print "original array: " , join ('--',@array) , "\n";
 
my $first_element = shift @array;
print "this was the first element: $first_element\n";
 
print "current array:  " , join ('--',@array) , "\n";

Output:

%% ./array_functions.pl
original array: 3--red--cornflower blue--1.2
this was the first element: 3
current array:  red--cornflower blue--1.2

unshift

  • Adds an element or a list to the front of the array
1
2
3
4
5
my @array = (3 , 'red' , 'cornflower blue' , 1.2);
print "original array: " , join ('--',@array) , "\n";
 
unshift (@array, 5, 'green', 10);
print "current array:  " , join ('--',@array) , "\n";

Output:

%% ./array_functions.pl
original array: 3--red--cornflower blue--1.2
current array:  5--green--10--3--red--cornflower blue--1.2

Exercises

  1. Create an array and print the array using join.
  2. Use the following functions, pop, push, shift, and unshift, on the array and print the array after each change.

Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *