Adding and Removing Elements in Perl Array


Perl provides a number of useful functions to add and remove elements in an array. You may have a question what is a function? So far you have used the print function to print various values. Similarly, there are various other functions or sometimes called subroutines, which can be used for various other functionalities.

Sr.No.Types & Description
1push @ARRAY, LIST
Pushes the values of the list onto the end of the array.
2pop @ARRAY
Pops off and returns the last value of the array.
3shift @ARRAY
Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down.
4unshift @ARRAY, LIST
Prepends list to the front of the array, and returns the number of elements in the new array.

Example

 Live Demo

#!/usr/bin/perl
# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";

# add one element at the end of the array
push(@coins, "Penny");
print "2. \@coins = @coins\n";

# add one element at the beginning of the array
unshift(@coins, "Dollar");
print "3. \@coins = @coins\n";

# remove one element from the last of the array.
pop(@coins);
print "4. \@coins = @coins\n";

# remove one element from the beginning of the array.
shift(@coins);
print "5. \@coins = @coins\n";

Output

This will produce the following result −

1. @coins = Quarter Dime Nickel
2. @coins = Quarter Dime Nickel Penny
3. @coins = Dollar Quarter Dime Nickel Penny
4. @coins = Dollar Quarter Dime Nickel
5. @coins = Quarter Dime Nickel

Updated on: 28-Nov-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements