The following post explains the concepts of push, pop, unshift, shift and sort functions in perl scripting.
Array : Array is a collection of elements. its elements are numbered from 0 to n-1.
pop - Removes the last element from the array.
push - insert given element(s) to the end of the array.
unshift - Inserts the given element(s) to the beginning of the array.
shift - removes the first element of the array.
sort - sorts the array in alphabetical order.
Syntax:
pop @array_name;
push @array_name, element(s)_to_be_inserted;
unshift (@array_name, "element(s)_to_be_inserted");
shift @array_name;
my @array_name = sort @array_name;
Here is a simple example.
#!/usr/bin/perl
#Purpose - To understand the concepts of Common array functions.
#PUSH POP SHIFT UNSHIFT and SORT
#START
#Modules using
use strict;
my @array = ("1","2","3","4");
print "The initial array elements are : @array\n";
#popping an element from the array.
my $popped_element = pop @array;
print "The array elements after popping are : @array\n";
print "The popped element is : $popped_element\n";
#Pushing the popped element back to the array.
push @array, $popped_element;
print "The array elements after pushing are : @array\n";
push @array, 5, 6, 7, 8;
print "The array elements after pushing 5, 6, 7, 8 are : @array\n";
#Unshift : Unshifting means it'll add the specified element to the begining of the array
print "unshifting the array with element : 0\n";
unshift (@array, "0");
print "Array elements after unshifting are : @array\n";
#shift : shift removes the first element from the array.
shift @array;
print "The elements after the operation shift are : @array\n";
#Sorting the elements of an array.
my @array1 = ("Randeep", "Saju", "Remil", "Ajith", "Nibul" );
print "The array1 before sorting is : @array1\n";
my @array1 = sort @array1;
print "The array1 after sorting is : @array1\n";
#END
No comments:
Post a Comment