Adding and Removing Elements in Array
Perl provides a number of useful functions to add and remove elements in an array.
S.N.
|
Types and
Description
|
1
|
push @ARRAY, LIST
Pushes the values of the list onto the end of the array. |
2
|
pop @ARRAY
Pops off and returns the last value of the array. |
3
|
shift @ARRAY
Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down |
4
|
unshift @ARRAY, LIST
Pretends list to the front of the array, and returns the number of elements in the new array. |
#! /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";This will produce 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
No comments:
Post a Comment