ashvak
ashvak

Reputation: 7

Perl array element comparing

I am new in Perl programming. I am trying to compare the two arrays each element. So here is my code:

#!/usr/bin/perl
use strict;
use warnings;
use v5.10.1;

my @x = ("tom","john","michell");
my @y = ("tom","john","michell","robert","ricky");
if (@x ~~ @y)
{
    say "elements matched"; 
}
else 
{ 
    say "no elements matched";
}

When I run this I get the output no elements matched

So I want to compare both array elements in deep and the element do not matches, those elements I want to store it in a new array. As I can now compare the only matched elements but I can't store it in a new array.

How can I store those unmatched elements in a new array?

Please someone can help me and advice.

Upvotes: 0

Views: 1261

Answers (2)

fugu
fugu

Reputation: 6568

I'd avoid smart matching in Perl - e.g. see here

If you're trying to compare the contents of $y[0] with $x[0] then this is one way to go, which puts all non-matches in an new array @keep:

use strict;
use warnings;
use feature qw/say/;

my @x = qw(tom john michell);
my @y = qw(tom john michell robert ricky);

my @keep;
for (my $i = 0; $i <$#y; $i++) {
    unless ($y[$i] eq $x[$i]){
        push @keep, $y[$i];
    }
}

say for @keep;

Or, if you simply want to see if one name exists in the other array (and aren't interested in directly comparing elements), use two hashes:

my (%x, %y);

$x{$_}++ for @x;
$y{$_}++ for @y;

foreach (keys %y){
    say if not exists $x{$_};
}

Upvotes: 5

Dave Cross
Dave Cross

Reputation: 69224

It would be well worth your while spending some time reading the Perl FAQ.

Perl FAQ 4 concerns Data Manipulation and includes the following question and answer:

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:

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;
}

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

Upvotes: 1

Related Questions