How to remove an element of array in foreach loop?

perl

Solution

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";
}

Problem

I want to loop through an array and check if some elements is equal to a specific condition . For example , I want to remove the element contains `"O"` , so I can do in this way .. ``` @Array = ("Apple","Orange","Banana"); for ($i=0 ; $i <= $#Array ; $i++) { if( index($Array[$i],"O") >= 0 ) { splice(@Array,$i,1); } } ``` but if I want to use `foreach` loop to replace `for` loop , how do I do ? because in `foreach` loop , there is no index so I can't use `splice` , unless I set a variable to store it .

Original source