in reply to Yet More fun With Array Indices
Or, if you use $_ and a for loop:foreach my $index (0..$#array) { if ($array[$index] == $whatever) { splice @array, $index, 1; } }
One last choice to build: using an if statement modifierfor (0..$#array) { if ($array[$_] == $whatever) { splice @array, $_, 1; } }
Except all of these are really flawed, because it skips elements. Removing an element makes all the future indices one shorter than they really are. An array of (1, 2, 1, 1, 2) will be changed to (2, 1, 2) if $whatever equals 1, because it skips around. To fix this, iterate backwards through the array, like so:for (0..$#array) { splice @array, $_, 1 if $array[$_] == $whatever; }
for (reverse 0..$#array) { splice @array, $_, 1 if $array[$_] == $whatever; }
elusion : http://matt.diephouse.com
|
|---|