Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract an array from an array?

Tags:

When I try the following

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @bl = qw(red green blue);
my @a = qw(green yellow purple blue pink);

print Dumper [grep {not @bl} @a];

I get an empty array. I would have expected that @bl was subtracted from @a, so the output was yellow purple pink.

What's wrong here?

like image 882
Sandra Schlichting Avatar asked Feb 03 '11 21:02

Sandra Schlichting


People also ask

How do you subtract one array from another array in Python?

subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise.

Can we subtract two arrays in C++?

If you are mentioning the subtraction of the elements that have the same indexes, you have to make sure that the array's size is equal. Then iterate through both arrays and subtract one to another using loop. The thing you want to achieve results in undefined behavior.

Can we subtract two arrays in Java?

In this program, we need to get the result of subtraction of two matrices. Subtraction of two matrices can be performed by looping through the first and second matrix. Calculating the difference between their corresponding elements and store the result in the third matrix.


2 Answers

You need to turn @bl into a hash to perform the set difference:

my %in_bl = map {$_ => 1} @bl;
my @diff  = grep {not $in_bl{$_}} @a;
like image 153
Eric Strom Avatar answered Oct 06 '22 03:10

Eric Strom


See perlfaq4: How do I compute the difference of two arrays?

In your code, not is probably not doing what you think it is doing.

not @bl will always be 1 if @bl is an empty array, and undef if @bl is not empty. It doesn't mean "elements not in @bl" in any sense.

like image 31
mob Avatar answered Oct 06 '22 04:10

mob