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?
subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise.
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With