Can someone please explain why push behaves the way as shown below?
Basically I am trying to print values of an array populated by push
as well unshift
.
When I try to print array contents populated by push
using array indexes, It always prints the element at the top of the array, whereas array populated by unshift
prints contents of array based on array index. I don't understand why.
with unshift
#!/usr/bin/perl
@names = ("Abhijit","Royal Enfield","Google");
@numbers=();
$number=1;
$i=0;
foreach $name (@names) {
#print $_ . "\n";
$number=$number+1;
#push(@numbers,($number));
unshift(@numbers,($number));
print("Array size is :" . @numbers . "\n");
$i=$i+1;
print("Individual Elements are:" . @numbers[i] . "\n");
pop(@numbers);
}
rhv:/var/cl_ip_down>./run.sh
Array size is :1
Individual Elements are:2
Array size is :2
Individual Elements are:3
Array size is :3
Individual Elements are:4
without unshift
#!/usr/bin/perl
@names = ("Abhijit","Royal Enfield","Google");
@numbers=();
$number=1;
$i=0;
foreach $name (@names) {
#print $_ . "\n";
$number=$number+1;
push(@numbers,($number));
#unshift(@numbers,($number));
print("Array size is :" . @numbers . "\n");
$i=$i+1;
print("Individual Elements are:" . @numbers[i] . "\n");
}
rhv:/var/cl_ip_down>./run.sh
Array size is :1
Individual Elements are:2
Array size is :2
Individual Elements are:2
Array size is :3
Individual Elements are:2
/without pop/
#!/usr/bin/perl
@names = ("Abhijit","Royal Enfield","Google");
@numbers=();
$number=1;
$i=0;
foreach $name (@names) {
#print $_ . "\n";
$number=$number+1;
#push(@numbers,($number));
unshift(@numbers,($number));
print("Array size is :" . @numbers . "\n");
$i=$i+1;
print("Individual Elements are:" . @numbers[i] . "\n");
#pop(@numbers);
}
rhv:/var/cl_ip_down>./run.sh
Array size is :1
Individual Elements are:2
Array size is :2
Individual Elements are:3
Array size is :3
Individual Elements are:4
with pop
#!/usr/bin/perl
@names = ("Abhijit","Royal Enfield","Google");
@numbers=();
$number=1;
$i=0;
foreach $name (@names) {
#print $_ . "\n";
$number=$number+1;
#push(@numbers,($number));
unshift(@numbers,($number));
print("Array size is :" . @numbers . "\n");
$i=$i+1;
print("Individual Elements are:" . @numbers[i] . "\n");
pop(@numbers);
}
rhv:/var/cl_ip_down>./run.sh
Array size is :1
Individual Elements are:2
Array size is :1
Individual Elements are:3
Array size is :1
Individual Elements are:4