Posts Tagged ‘shift’

Perl: Array operations, push,pop,shift,unshift,scalar keyword.

April 5, 2013

#Array operations PUSH,#POP,shift,unshift,sorting #and use of scalar #keyword for
#getting the length of array;
#arr1 is 2 dimensional array.
use strict;

my @arr1 = ( [“kk”, “KJK”, “KD”],
[“MK”, “MJK”, “MN”]) ;

print “Original arr1 is :\n” ;
print @$_,”\n \n” foreach @arr1;

print “\n\n added element using unshift operator”;
unshift (@arr1[0] , “kedarKOOL”);
print “\n\n now arr1 is:\n”;
print @$_, foreach @arr1 ;

print “\n\n removed element using shift operator”;
shift (@arr1[0]);
print “\n\n now arr1 is\n”;
print @$_,”\n” foreach @arr1 ;

print “now push pop results” ;

my @arr2 = ( “MANDAR4″,”KK”,”3d”,”KEDAR1″);
print “\n \n original arr2 is :\n” ;

foreach my$arr2(@arr2) {
print $arr2,”\t”;
}

push (@arr2,”kjk”);
print “\n\n added element using push operator. \n Now arr2 is:\n” ;

foreach my $arr2element (@arr2)
{ print “\t”, $arr2element ;
} ;

print “\n\n removed element using pop operator. \n Now arr2 is:\n” ;
pop (@arr2);
print “\n” ;
foreach my $arr2element (@arr2)
{ print “\t”, $arr2element ;
} ;

print “\n\n Joining the array with :: looks like this ->”, join (“::”,@arr2);
my $str1 = ” This is one string”;
print “\n”,$str1;
my @arr4 = split / /,$str1;
print “\n Strings splitted array is:”;
foreach my $arr4 (@arr4)
{
print $arr4, “\t”;
}

my @arr3 = @arr2[0,2,3];
print “\n\n original arr3 is:\n @arr3”;

@arr2 = sort(@arr3);
print “\n sorted arr3 is :\n @arr2”;

print “\n Length of arr2 is :”,scalar(@arr2), “\n”;
print ” Length of arr1 is :”,scalar(@arr1), “\n”;

Advertisements