The reason the last element hasn't been counted for you is because $#array_name does NOT return the length of an array. Rather, it returns the last index of an array. This means that for an 8-element array, it will return 7, since the first index is always 0. To get the length of an array in a scalar index, you can simply use @array_name. You can also force scalar output with the scalar function, ie scalar( @array_name ).
Now, as spooon pointed out in his link, the variable you were looking for in your foreach loop was $_, which is the default variable perl uses in many of its built-in functions. However, as he also mentioned, it is against convention to manipulate array elements in foreach loops. If you wish to actually change array values, use a for-loop. Foreach loops should be reserved for occasions when your array elements remain unchanged.
Here is a version of your code that should work. I actually opted for a while-loop over a for-loop after testing though, as a for-loop would require $i to be decremented in order to work properly. Otherwise, the element directly after e would be skipped. However, it's not good form to manipulate the control variable in a for-loop. Thus, I felt a while variant was in order.
Code:
#!/usr/bin/perl
use strict;
use warnings;
my @abc = ('a' .. 'h');
print "There are ", scalar(@abc), " elements in \@abc\n";
my $pointer = 0;
while ($pointer <= $#abc) {
print "\@abc[$pointer] is $abc[$pointer]\n";
if ($abc[$pointer] eq 'e') {
print "E must be removed.\n";
splice(@abc, $pointer, 1);
}
else {
$pointer++;
}
}
print "There are ", scalar(@abc), " elements in \@abc\n";
foreach (@abc) {
print "$_\n";
}
And the output:
Code:
There are 8 elements in @abc
@abc[0] is a
@abc[1] is b
@abc[2] is c
@abc[3] is d
@abc[4] is e
E must be removed.
@abc[4] is f
@abc[5] is g
@abc[6] is h
There are 7 elements in @abc
a
b
c
d
f
g
h
Hope that helps...