How can I compare arrays in Perl?

后端 未结 12 2110
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 19:17

    Brute force should do the trick for small a n:

    my $flag = 0;
    foreach my $i (@a) {
        foreach my $k (@b) {
            if ($i eq $k) {
                $flag = 1;
                last;
            }
        }
    }
    

    For a large n, use a hash table:

    my $flag   = 0;
    my %aa     = ();
       $aa{$_} = 1 foreach (@a);
    foreach my $i (@b) {
        if ($aa{$i}) {
            $flag = 1;
            last;
        }
    }
    

    Where a large n is |@a| + |@b| > ~1000 items

提交回复
热议问题