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

Monks,

I have two arrays @a and @b, i want to remove the similar elements in both arrays and retain the dissimilar elements.

@a = (2, 6.5 ,4, 3, 2, 7.5, 4.0); @b = (2, 6.52 ,4.5, 7.05, 2.0, 4.1, 3);

The output i need is:

@a = (6.5, 4, 7.5, 4.0) @b = (6.52, 4.5, 7.05, 2.0, 4.1)

How can we attain this.

Replies are listed 'Best First'.
Re: Remove similar elements in both the array
by data64 (Chaplain) on Mar 08, 2005 at 05:07 UTC
Re: Remove similar elements in both the array
by tilly (Archbishop) on Mar 08, 2005 at 04:38 UTC
    my %in_a; my %in_b; undef @in_a{@a}; undef @in_b{@b}; @a = grep {not exists $in_b{$_}} @a; @b = grep {not exists $in_a{$_}} @b;
    Update: I guess that I do need the braces after all, as davis noted I didn't run the code. Sorry.
      @a = grep not exists $in_b{$_}, @a; @b = grep not exists $in_a{$_}, @b;

      According to my perl:

      Not enough arguments for grep at j.pl line 14, near "@a;" Execution of j.pl aborted due to compilation errors.
      I think you want:
      #!/usr/bin/perl use warnings; use strict; use Data::Dumper; my @a = (2, 6.5 ,4, 3, 2, 7.5, 4.0); my @b = (2, 6.52 ,4.5, 7.05, 2.0, 4.1, 3); my %in_a; my %in_b; undef @in_a{@a}; undef @in_b{@b}; @a = grep {not exists $in_b{$_}} @a; @b = grep {not exists $in_a{$_}} @b; print Dumper(\@a); print Dumper(\@b);

      davis
      It wasn't easy to juggle a pregnant wife and a troubled child, but somehow I managed to fit in eight hours of TV a day.