Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: Yet More fun With Array Indices

by elusion (Curate)
on Sep 14, 2002 at 16:47 UTC ( #197891=note: print w/replies, xml ) Need Help??

in reply to Yet More fun With Array Indices

Something like this perhaps?
foreach my $index (0..$#array) { if ($array[$index] == $whatever) { splice @array, $index, 1; } }
Or, if you use $_ and a for loop:
for (0..$#array) { if ($array[$_] == $whatever) { splice @array, $_, 1; } }
One last choice to build: using an if statement modifier
for (0..$#array) { splice @array, $_, 1 if $array[$_] == $whatever; }
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 (reverse 0..$#array) { splice @array, $_, 1 if $array[$_] == $whatever; }

elusion :

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://197891]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2019-07-18 06:42 GMT
Find Nodes?
    Voting Booth?

    No recent polls found