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

#!/fellow/monks.pl

A collegue of mine asked me "How do you delete an entry out of an array?" I know that "delete" can zap an entry out of a hash, but what do you use to delete an entry out of an array? He went and wrote this piece of code, which does the trick pretty well.

Is there a single line perl statement, like delete that will do the same thing? My "Programming Perl" didn't reveal anything obvious.

sub delArrayEntry() { my @array1 = @_; my @array2 = ""; foreach $entry (@array1) { if ($entry ne $current_log) { push @array2,$entry } } }

Thanks!

#!/massyn.pl

You never know important a backup is until the day you need it.

Replies are listed 'Best First'.
Re: Deleting an array entry
by dws (Chancellor) on Nov 28, 2002 at 04:31 UTC
    A collegue of mine asked me "How do you delete an entry out of an array?"

    And you didn't remember "splice" until later that evening. Don't you hate it when that happens? :)

Re: Deleting an array entry
by pg (Canon) on Nov 28, 2002 at 05:00 UTC
    • If you want to delete by index, try splice. For example, the following code removes the element at index 10:
      splice(@array, 10, 1);
    • If you want to delete by value, then your trick is fine, but grep might be better. For example, the following code deletes 10, which has two digits:
      @old_array = (1,2,3,4,5,10,6,7,8,9); @new_array = grep(/^\d$/, @old_array);
Re: Deleting an array entry
by bart (Canon) on Nov 28, 2002 at 07:03 UTC
    Congratulations, you've just reinvented a limited version of grep().
    @filtered = grep { $_ ne $current_log } @original;

    If instead, you have an array index instead of a condition, use splice(). The next will delete the third item:

    splice @array, 2, 1;
    This modifies the original array, instead of making a filtered copy. Well, you can always use an array slice:
    @filtered = @original[grep { $_ != 2 } 0 .. $#original];
    The grep makes a complete list of all array items, from 0 to $#original, but without the 2.
      Here is the code i use:
      for (my $i = 0; $i < @array};$i++) { if ($array($i) eq $nick) { splice(@array},$i,$i+1); last; } }

      But I really havent done much array element removing (just read about splice yesterday ;)).

      ^jasper
Re: Deleting an array entry
by rbc (Curate) on Nov 28, 2002 at 04:34 UTC
    You may want to play around with splice.
    perldoc -f splice
Re: Deleting an array entry
by chromatic (Archbishop) on Nov 29, 2002 at 00:38 UTC
    my @array2 = "";

    This is probably not what you want; it creates a single-element array.