How to remove an element of array in foreach loop?
If you want to remove elements, the better tool is grep
:
@array = grep { !/O/ } @array;
Technically, it is possible to do with a for
loop, but you'd have to jump through some hoops to do it, or copy to another array:
my @result;
for (@array) {
if (/O/) {
push @result, $_;
}
}
You should know that for
and foreach
are aliases, and they do exactly the same thing. It is the C-style syntax that you are thinking of:
for (@array) { print $_, "\n"; } # perl style, with elements
for (my $x = 0; $x <= $#array; $x++) { # C-style, with indexes
print $array[$x], "\n";
}