Social Icons

Pages

Wednesday 24 September 2014

Perl Arrays: push, pop, shift and unshift functions

Perl provides many functions to manipulate and access arrays. These functions makes it very easy to use perl arrays as stacks or queue's. Some of these functions are given below:

POP: 

pop function will remove and return last element of perl arrays. So, this can be used to remove element from stack if array is getting used as stack. pop function will return undef if array is empty

Example:

my @arr = ("abc","def","ghi","jkl");
my $last=pop @arr;
print $last;
OUTPUT: jkl

PUSH: 

push function will add element to last of an array. So, this can be used to add element to stack/queue if array is getting used as stack/queue.
Example:

my @arr = ("abc");
push @arr, "def";
print $arr[1];
OUTPUT: def

shift: 

shift function will return and remove first element of an array. So, this can be used to remove element to queue if array is getting used as queue.
Example:

my @arr = ("abc","def");
my $first = shift @arr;
print $first;
OUTPUT: abc

unshift: 

unshift function will add given element as first element of an array.
Example:

my @arr = ("abc","def");
unshift @arr,"soh";
print $arr[0];
OUTPUT: soh

No comments:

Post a Comment

Please Comment for Any question or suggestions