8

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 .

2
  • 2
    for and foreach is the exact same thing, they are aliases. It is the C-style syntax that makes a difference. Commented Jul 20, 2013 at 12:37
  • your code is buggy; if there are more than one elements in a row containing "O", only the odd ones will be removed. Commented Jul 22, 2013 at 0:27

3 Answers 3

20

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"; } 
Sign up to request clarification or add additional context in comments.

Comments

2

BTW, you can still use a foreach-style for loop to process and remove elements — without having to build a whole new array...

Just work backwards from beginning-to-end:

#!/usr/bin/env perl use strict; use warnings; use 5.010; my @fruits = qw< Apple Orange Banana >; for my $index ( reverse 0 .. $#fruits ) { my $item = $fruits[$index]; if ( $item =~ /^O/ ) { # Do something... say "Removing #$index: $item"; # Remove the current item... splice @fruits => $index, 1; } } 

Or, in the spirit of TMTOWTDI:

say "Removing #$_: " . splice @fruits => $_, 1 for grep $fruits[$_] =~ /^O/, reverse 0 .. $#fruits; 

Comments

0

In case your for loop does other things than just remove elements, you could 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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.