Flyghost has asked for the wisdom of the Perl Monks concerning the following question:

Would like to delete the element out of an array, but don't know how to findout what the current_element (offset) is. I guess it would be something like this ?
foreach $line (@array) { @temp = split(/ /,$line); if ( $temp[0] eq "test") { splice(@array, $current_element ,1); } }

Replies are listed 'Best First'.
RE: remove current element out array
by Russ (Deacon) on May 19, 2000 at 05:16 UTC
    This type of problem is what grep was made for...
    In this example, grep will return (back into @Array) every line in @Array which does not start with 'test'.
    my @Array = grep {substr($_, 0, 4) ne 'test'} @Array;
    You seem to be just testing for the string 'test' at the front of each line. Just modify grep's conditional as appropriate.

    Russ

    P.S. You normally shouldn't modify the list used in a for(each).

Re: remove current element out array
by comatose (Monk) on May 19, 2000 at 19:28 UTC

    If you want to know the current element in a foreach loop, you could easily switch to a for loop. In this case $i is your array index.

    for ($i = 0; $i < scalar @array; $i++) { ... }

    Here's something else you could do. As always, there's more than one way to do it.

    sub removeJunk { my @stuff = @_; my (@keepers); while (my $value = pop @stuff) { @keepers = (@keepers, $value) if ($value =~ /^test\s/); } return @keepers; }

    If you have a really big array, you will want to use references.

      You wouldn't want to use the for loop with a splice - that would incrememnt the $i counter AND move up all the array's elements, causing an elemnet to be skipped.