Foreach loop.

They have: 62 posts

Joined: May 2000

OK, here it goes. I have a foreach loop. I want it to match a variable and delete the item in the array that was matched. This is what I have.

foreach $item (@array) {
if ($item eq "$variable") {
$item=~s/$item//gi;
}
}

Yet the item is never deleted. How do i do this?

They have: 453 posts

Joined: Jan 1999

foreach gives you a copy of each element in the array.

your "nifty" regex/substitution replaces the "$variable" in $item (which only consists of $variable) with nothing.
So why not just write $item=""; ?

You can put all items of the array that you want to keep into a new array.

my @array2 = ( );
foreach $item( @array ){
  if( $item ne $variable ){
    push( @array2, ( $item ) );
  }
}
'

As usually untested, since I don't have perl on this box

ciao
Anti

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.