如何在perl中使用数组匹配两个序列

前端之家收集整理的这篇文章主要介绍了如何在perl中使用数组匹配两个序列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
循环遍历两个数组时,我对如何将指针移动到一个循环但在另一个循环中保持不变感到困惑.例如:

>阵列1:A T C G T C G A G C G.
>阵列2:A C G T C C T G C C G.

因此,第一个数组中的A与第二个数组中的A匹配,因此我们继续使用下一个元素.但由于T与第二个索引中的C不匹配,我希望程序将该T与阵列2中的下一个G进行比较,依此类推,直到找到匹配的T.

my ($array1ref,$array2ref) = @_;

my @array1 = @$array1ref;
my @array2= @$array2ref;
my $count = 0; 
foreach my $element (@array1) {
 foreach my $element2 (@array2) {
 if ($element eq $element2) {
 $count++;
  }else { ???????????


}

解决方法

您可以使用while循环来搜索匹配项.如果找到匹配项,请在两个阵列中前进.如果不这样做,请前进第二个阵列.最后,您可以打印第一个数组中剩余的不匹配字符:

# [1,2,3] is a reference to an anonymous array (1,3)
# qw(1,3) is shorthand quoted-word for ('1','2','3')
my $arr1 = [qw(A T C G T C G A G C G)];
my $arr2 = [qw(A C G T C C T G T C G)];

my $idx1 = 0;
my $idx2 = 0;

# Find matched characters
# @$arr_ref is the size of the array referenced by $arr_ref
while ($idx1 < @$arr1 && $idx2 < @$arr2) {
    my $char1 = $arr1->[$idx1];
    my $char2 = $arr2->[$idx2];
    if ($char1 eq $char2) {
        # Matched character,advance arr1 and arr2
        printf("%s %s  -- arr1[%d] matches arr2[%d]\n",$char1,$char2,$idx1,$idx2);
        ++$idx1;
        ++$idx2;
    } else {
        # Unmatched character,advance arr2
        printf(". %s  -- skipping arr2[%d]\n",$idx2);
        ++$idx2;
    }
}

# Remaining unmatched characters
while ($idx1 < @$arr1) {
    my $char1 = $arr1->[$idx1];
    printf("%s .  -- arr1[%d] is beyond the end of arr2\n",$idx1);
    $idx1++;
}

脚本打印:

A A  -- arr1[0] matches arr2[0]
. C  -- skipping arr2[1]
. G  -- skipping arr2[2]
T T  -- arr1[1] matches arr2[3]
C C  -- arr1[2] matches arr2[4]
. C  -- skipping arr2[5]
. T  -- skipping arr2[6]
G G  -- arr1[3] matches arr2[7]
T T  -- arr1[4] matches arr2[8]
C C  -- arr1[5] matches arr2[9]
G G  -- arr1[6] matches arr2[10]
A .  -- arr1[7] is beyond the end of arr2
G .  -- arr1[8] is beyond the end of arr2
C .  -- arr1[9] is beyond the end of arr2
G .  -- arr1[10] is beyond the end of arr2

猜你在找的Perl相关文章