in reply to Reducing array

This got me thinking - it's one of those timtowtdi thingies, but I thought this solution was quite nice - to begin with - look at this
# First, but @items into a hash instead though... my @array = qw(dog cat cow horse donkey chicken); my %items = qw(cat 1 donkey 1); # this is weird.. if this is true print "\$array[-4] = $array[-4]\n"; for (1..@array) { splice(@array, -$_, 1) if $items{ $array[-$_] }; } # and this is true print "\$array[-4] = $array[-4]\n"; # how come this is right??? print join ', ',@array, "\n";
And then I thought about it. Hang on. The array's getting spliced each time a match is made, so an index of -$_ would skip elements (ie $array[-4] before is 'cow', after, it's 'dog', which is expected, but... Weird thing is, it doesn't look like it should work. Anyone got any idea why this works when I think it shouldn't???

err

cLive ;-)

Replies are listed 'Best First'.
Re: (cLive ;-) Re: Reducing array
by jmcnamara (Monsignor) on May 09, 2002 at 10:42 UTC

    Anyone got any idea why this works...

    It doesn't work. You were just lucky. :-) Try:

    my %items = qw(horse 1 donkey 1); .. Prints: dog cat cow horse chicke

    --
    John.