gpt4 book ai didi

linux - 在 Perl 中查找两个等长字符串之间差异的快速方法

转载 作者:IT王子 更新时间:2023-10-29 01:01:16 24 4
gpt4 key购买 nike

给定这样的字符串对。

    my $s1 = "ACTGGA";
my $s2 = "AGTG-A";

# Note the string can be longer than this.

我想在 $s1 中找到与 $s2 不同的位置和字符。在这种情况下,答案是:

#String Position 0-based
# First col = Base in S1
# Second col = Base in S2
# Third col = Position in S1 where they differ
C G 1
G - 4

我可以使用 substr() 轻松实现。但它非常慢。通常我需要比较数百万个这样的对。

有没有快速的方法来实现?

最佳答案

Stringwise ^ 是你的 friend :

use strict;
use warnings;
my $s1 = "ACTGGA";
my $s2 = "AGTG-A";

my $mask = $s1 ^ $s2;
while ($mask =~ /[^\0]/g) {
print substr($s1,$-[0],1), ' ', substr($s2,$-[0],1), ' ', $-[0], "\n";
}

解释:

^(异或)运算符在字符串上使用时,返回由每个字符的数值的每一位异或的结果组成的字符串。将示例分解为等效代码:

"AB" ^ "ab"
( "A" ^ "a" ) . ( "B" ^ "b" )
chr( ord("A") ^ ord("a") ) . chr( ord("B") ^ ord("b") )
chr( 65 ^ 97 ) . chr( 66 ^ 98 )
chr(32) . chr(32)
" " . " "
" "

此处的有用特性是当且仅当两个字符串在给定位置具有相同字符时,才会出现 nul 字符 ("\0")。所以 ^ 可以用于一次快速操作高效地比较两个字符串的每个字符,并且可以在结果中搜索非 nul 字符(表示差异)。可以在标量上下文中使用/g 正则表达式标志重复搜索,并使用 $-[0] 找到每个字符差异的位置,这给出了最后一次成功匹配的开头的偏移量。

关于linux - 在 Perl 中查找两个等长字符串之间差异的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4709537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com