You can get the desired behavior with a couple of changes to your code.
- If you delete an element of the array, the index of the next element is now the same as the old value’s index. You can’t blindly iterate over
0 .. $#ref_to_spliceArray.
- The regex bind operator is
=~ and not ==.
- Attempted regex matches against the undefined value may trigger warnings.
- Pass an array to
splice, not an individual element of the array.
The code below fixes these issues.
sub removeElement
{
my $ref_to_spliceArray = shift;
my $i = 0;
while ($i <= $#$ref_to_spliceArray)
{
if (defined $ref_to_spliceArray->[$i]
&& $ref_to_spliceArray->[$i] =~ /failed/)
{
splice @$ref_to_spliceArray, $i, 1;
}
else {
++$i;
}
}
}
Modify your call to be
&removeElement(\@spliceArray);
Note that this syntax will appear archaic to modern eyes. Think about operating on the array as a whole rather than peeking and poking one element at a time. In this simple case, you don’t need to go to the trouble of defining another sub.
@spliceArray = grep !(defined && /failed/), @spliceArray;
That is, @spliceArray should contain only those elements that do not match the regex. The defined check prevents warnings about undefined values that may be present in @spliceArray.