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

I'm sure I could do this but I was hoping someone with more Perl knowledge can help me do it with fewer lines of code...I have an array of words that I want removed from an array of other words meaning...
@badWords=("jerk","store","king") @myArray=("jerry","wash","king","kong","store","when","jerk") I want to apply the function and get back: @myArray=("jerry","wash","kong","when")
THANKS for any help to this newbie!

Edit: chipmunk 2001-06-28

Replies are listed 'Best First'.
Re: Easy one: removing elements of one array from another...
by snowcrash (Friar) on Jun 28, 2001 at 09:38 UTC
    my %remove = map { $_ => 1 } @badWords; my @goodWords = grep(!defined $remove{$_}, @myArray);

    Next time, please try Super Search or look at the chapter on arrays in the Q&A section.
    snowcrash //////
      Alternatively, one could use delete. This code also removes any duplicates from @myarray.
      #!/opt/perl/bin/perl -w use strict; my @badwords = qw /jerk store king/; my @myarray = qw /jerry wash king kong store when jerk/; @@ {@myarray} = (); delete @@ {@badwords}; @myarray = keys (%@); print "@myarray\n"; __END__

      -- Abigail

        Taken from Perl Cookbook 4.7:

        #!/apps/bin/perl -w use strict; # Taken from Perl Cookbook 4.7 Finding Elements in One Array but # not another my %seen = (); # look up table my @goodWords; # words you want my @badWords=("jerk","store","king"); my @myArray=("jerry","wash","king","kong","store","when","jerk"); @seen{@badWords} = (); # build lookup table my $item; foreach $item (@myArray) { push (@goodWords, $item) unless exists $seen{$item}; } # print the contents of goodWords foreach (@goodWords) { print "$_\t"; } print "\n";