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

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

i need an array only with the difference between two arrays.
in perl 5.10

@diff = grep { ! ({ \$_, 0 } ~~ @inst) } @insttab;

how i do it without Smart Matching ? in perl 5.8

Replies are listed 'Best First'.
Re: get the Difference between two arrays
by davido (Cardinal) on Apr 02, 2018 at 18:53 UTC

This is addressed in perlfaq4 at How do I compute the difference of two arrays. The code there could be adapted to your specific need pretty easily.

Here's the code from perlfaq4:

``` my (@union, @intersection, @difference);
my %count = ();
foreach my \$element (@array1, @array2) { \$count{\$element}++ }
foreach my \$element (keys %count) {
push @union, \$element;
push @{ \$count{\$element} > 1 ? \@intersection : \@difference }
+, \$element;
}

Here's one way to adapt it.

```sub difference {
my \$array_ref1 = shift;
my \$array_ref2 = shift;
my @difference;

foreach my \$element (@\$array_ref1, @\$array_ref2) { \$count{\$element
+}++ };
foreach my \$element (keys %count) {
push @difference, \$element if \$count{\$element} == 1;
}
return \@difference;
}

(please do test it -- this is untested code.)

Dave

Re: get the Difference between two arrays
by Cristoforo (Curate) on Apr 02, 2018 at 18:33 UTC
Hi gabrielsousa,

List::Compare and Set::Scalar will do this.

The method you want is get_symmetric_difference for List::Compare or symmetric_difference for Set::Scalar.

And the faq that KurtZ referenced.

```
C:\Old_Data\perlp>perldoc -q "intersection"
Found in C:\Perl64\lib\pods\perlfaq4.pod
How do I compute the difference of two arrays?  How do I compute the
+ intersection of two arrays?
Use a hash. Here's code to do both and more. It assumes that each
element is unique in a given array:

@union = @intersection = @difference = ();
%count = ();
foreach \$element (@array1, @array2) { \$count{\$element}++ }
foreach \$element (keys %count) {
push @union, \$element;
push @{ \$count{\$element} > 1 ? \@intersection : \@
+difference }, \$element;
}

Note that this is the *symmetric difference*, that is, all element
+s in
either A or in B but not in both. Think of it as an xor operation.

C:\Old_Data\perlp>
Re: get the Difference between two arrays
by KurtZ (Friar) on Apr 02, 2018 at 18:26 UTC
Use hash slices to create hashes and delete via hash slice. See Perl faq for a conventional solution.
> Use hash slices to create hashes and delete via hash slice.

like this Using hashes for set operations... ? :)

##### update

```use strict;
use warnings;
use Data::Dump qw/pp dd/;

my @Llist = qw(abel abel baker camera delta edward fargo golfer);
my @Rlist = qw(baker camera delta delta edward fargo golfer hilton);

my %tmp;

@tmp{@Rlist} = @Rlist;

delete @tmp{@Llist};

pp values %tmp;