How to remove an element of an array in a foreach loop?

I want to loop through an array and check if some elements are equal to a specific condition. For example, I want to delete an element containing "O" , so I can do this.

 @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 the foreach to replace the for loop, how do I do this? because there is no index in the foreach , so I cannot use splice unless I set a variable to store it.

+5
source share
2 answers

If you want to remove items, the best tool would be grep :

 @array = grep { !/O/ } @array; 

Technically, it is possible to do this with a for loop, but you will have to jump over some hoops to do this, 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 the same. This is the C-style syntax 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"; } 
+17
source

In case your for loop does something other than just deleting elements, you can do something like this:

 @Array = ("Apple","Orange","Banana"); @del = (); for my $i (0..$#Array) { # do your stuff unshift @del, $i if ($Array[$i] eq "Orange"); } map { splice @Array, $_, 1 } @del; 
0
source

Source: https://habr.com/ru/post/1492464/


All Articles