How can I compare arrays in Perl?

后端 未结 12 2087
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 18:54

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\";
m         


        
12条回答
  •  -上瘾入骨i
    2020-12-06 19:27

    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.

提交回复
热议问题