0

I have an array which contains several strings. There is another array which contains strings which may or may not be contained in the first array.

What is the best way to remove any instances of a string in array b from the strings in array a. I have tried to use grep as in the example below but it completely empties the array.

my @Aray = ('Chris', 'John', 'Paul', 'Max', 'Jim', 'John');
my @Bray = ('Chris', 'John');
foreach $name (@Bray){
    @Aray = grep {$_ != $name} @Aray;
}

This would result in no elements left in @Aray, opposed to 'Paul', 'Max', 'Jim'

I also tried with a traditional for loop and indexing each name in @Bray with the same result.

4
  • 6
    Use ne instead of != for strings. Commented Feb 17, 2016 at 16:53
  • 1
    perldoc.perl.org/… Commented Feb 17, 2016 at 16:58
  • 1
    and always use warnings; Commented Feb 17, 2016 at 18:06
  • because not doing so is like skydiving without a parachute. compare perl -E"use warnings; say 'a' != 'b' ? 'not equal' : 'equal'" to perl -E"say 'a' != 'b' ? 'not equal' : 'equal'" Commented Feb 18, 2016 at 20:51

1 Answer 1

6

@choroba shows above how to solve the specific problem you are asking.

Deleting elements of one array based on the elements on another is a common problem in Perl, and there is a useful idiom that speeds up such operations. Specifically:

  1. Place the elements you want to delete (Array B) in a Hash H.
  2. Loop over Array A and test whether any of its elements are in Hash H, if so delete them, otherwise keep them

This method has the benefit of only reading the delete array (Array B) a single time instead of for every element of Array A

my @Aray = ('Chris', 'John', 'Paul', 'Max', 'Jim', 'John');
my @Bray = ('Chris', 'John');

my %to_delete = map { $_ => 1 } @Bray;
@Aray = grep { ! $to_delete{$_} } @Aray;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.