Friday, March 25, 2011

How to compare 2 arrays and differences store in 3 array

#!/usr/bin/perl
use strict;
use warnings;
use List::Compare;

my @new = qw/a b c d e/;
my @old = qw/a b   d e f/;

my $lc = List::Compare->new(\@new, \@old);

# an array with the elements that are in @new and not in @old : c
my @Lonly = $lc->get_Lonly;
print "\@Lonly: @Lonly\n";

# an array with the elements that are not in @new and in @old : f
my @Ronly = $lc->get_Ronly;
print "\@Ronly: @Ronly\n";

# an array with the elements that are in both @new and @old : a b d e
my @intersection = $lc->get_intersection;
print "\@intersection: @intersection\n";

__END__
** prints

@Lonly: c
@Ronly: f
@intersection: a b d e


OR


#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @new = qw/a b c d e/;
my @old = qw/a b   d e f/;
my %new = map{$_ => 1} @new;
my %old = map{$_ => 1} @old;

my (@new_not_old, @old_not_new, @new_and_old);
foreach my $key(@new) {
    if (exists $old{$key}) {
        push @new_and_old, $key;
    } else {
        push @new_not_old, $key;
    }
}
foreach my $key(@old) {
    if (!exists $new{$key}) {
        push @old_not_new, $key;
    }
}

print Dumper\@new_and_old;
print Dumper\@new_not_old;
print Dumper\@old_not_new;

No comments: