How can I compare arrays in Perl?

2020-02-01 07:27发布

I have two arrays, @a and @b. I want to do a compare among the elements of the two arrays.

my @a = qw"abc def efg ghy klm ghn";
my @b = qw"def ghy jgk lom com klm";

If any element matches then set a flag. Is there any simple way to do this?

标签: perl arrays
12条回答
smile是对你的礼貌
2楼-- · 2020-02-01 08:18

This question still could mean two things where it states "If any element matches then set a flag":

  1. Elements at the same position, i.e $a[2] eq $b[2]
  2. Values at any position, i.e. $a[3] eq $b[5]

For case 1, you might do this:

# iterate over all positions, and compare values at that position
my @matches = grep { $a[$_] eq $b[$_] } 0 .. $#a;

# set flag if there's any match at the same position 
my $flag = 1 if @matches;

For case 2, you might do that:

# make a hash of @a and check if any @b are in there
my %a = map { $_ => 1 } @a;
my @matches = grep { $a{$_} } @b;

# set flag if there's matches at any position 
my $flag = 1 if @matches;

Note that in the first case, @matches holds the indexes of where there are matching elements, and in the second case @matches holds the matching values in the order in which they appear in @b.

查看更多
够拽才男人
3楼-- · 2020-02-01 08:23

This is one way:

use warnings;
use strict;
my @a = split /,/, "abc,def,efg,ghy,klm,ghn";
my @b = split /,/, "def,ghy,jgk,lom,com,klm";
my $flag = 0;
my %a;
@a{@a} = (1) x @a;
for (@b) {
    if ($a{$_}) {
        $flag = 1;
        last;
    }
}
print "$flag\n";
查看更多
叛逆
4楼-- · 2020-02-01 08:25

List::Compare

if ( scalar List::Compare->new(\@a, \@b)->get_intersection ) {
    …
}
查看更多
叼着烟拽天下
5楼-- · 2020-02-01 08:26

From the requirement that 'if any element matches', use the intersection of sets:

sub set{
  my %set = map { $_, undef }, @_;
  return sort keys %set;
}
sub compare{
    my ($listA,$listB) = @_;
    return ( (set(@$listA)-set(@$listB)) > 0)
}
查看更多
We Are One
6楼-- · 2020-02-01 08:29

Check to create an intersect function, which will return a list of items that are present in both lists. Then your return value is dependent on the number of items in the intersected list.

You can easily find on the web the best implementation of intersect for Perl. I remember looking for it a few years ago.

Here's what I found :


my @array1 = (1, 2, 3);
my @array2 = (2, 3, 4);
my %original = ();
my @isect = ();

map { $original{$_} = 1 } @array1;
@isect = grep { $original{$_} } @array2;

查看更多
Ridiculous、
7楼-- · 2020-02-01 08:29

This is Perl. The 'obvious' solution:

my @a = qw"abc def efg ghy klm ghn";
my @b = qw"def ghy jgk lom com klm";
print "arrays equal\n"
    if @a == @b and join("\0", @a) eq join("\0", @b);

given "\0" not being in @a.

But thanks for confirming that there is no other generic solution than rolling your own.

查看更多
登录 后发表回答