http://www.perlmonks.org?node_id=727555

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

hi all, can i delete a specific element from an array. Example,
@array=('water','wine','applepie','beer','orange juice') @dels=('apple','orange');
can i compare the elements one by one and delete the elements of @dels that match as a subset from the list of elements in @array?????

Replies are listed 'Best First'.
Re: deleting a specific element from an array
by kyle (Abbot) on Dec 03, 2008 at 02:17 UTC

    It's a good time for a hash and grep.

    my %delh; @delh{@dels} = (); @array = grep ! exists $delh{$_}, @array;
Re: deleting a specific element from an array
by GrandFather (Saint) on Dec 03, 2008 at 03:10 UTC

    List::Compare's get_unique member may help.

    use strict; use warnings; use List::Compare; my @array=('water','wine','apple','beer','orange'); my @dels=('apple','orange'); my $lc = List::Compare->new( { lists => [\@array, \@dels] } ); print join ', ', $lc->get_unique ();

    Prints:

    beer, water, wine

    Perl's payment curve coincides with its learning curve.
Re: deleting a specific element from an array
by ikegami (Patriarch) on Dec 03, 2008 at 03:10 UTC

    For some definition of "matches", the basic algorithm is

    my @out; for my $i (@in) { my $delete = 0; for my $d (@dels) { if (matches($i, $d)) { $delete = 1; last; } } push @out, $i if !$delete; }

    In your original question, you asked for equality, so "matches($i, $d)" would be "$i eq $d".

    In your updated question, you asked for substring presence, so "matches($i, $d)" would be "index($i, $d) >= 0" or "$i =~ /\Q$d\E/".

    The hash solution and the build-a-regexp solution are simply optimizations of the above algorithm.

Re: deleting a specific element from an array
by ikegami (Patriarch) on Dec 03, 2008 at 02:18 UTC

    You want to lookup if something is in the list of items to delete. Hashes are good for looking up strings.

    my %dels = map { $_ => 1 } @dels; @array = grep !$dels{$_}, @array;
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: deleting a specific element from an array
by lakshmananindia (Chaplain) on Dec 04, 2008 at 07:04 UTC
    You can also do as follows
    use Data::Dumper; my %hash=(water => 1, wine => 1, applepie => 1, beer => 1, orange => 1, juice => 1 ); print Dumper \%hash; @dels=('applepie','orange'); foreach (@dels) { delete $hash{$_}; } print Dumper \%hash;