1

我对 perl 和一般编程都很陌生。过去几天我一直在寻找如何计算模式匹配的数量;我很难理解其他解决方案并将它们应用于我已经编写的代码。

基本上,我有一个序列,我需要找到所有匹配 [TC]C[CT]GGAAGC 的模式

我相信我已经掌握了那部分。但我坚持计算每个模式匹配的出现次数。有谁知道如何编辑我已经必须这样做的代码?欢迎任何建议。谢谢!

#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;

# open fasta file for reading 
unless( open( FASTA, "<", '/scratch/Drosophila/dmel-all-chromosome-    r6.02.fasta' )) {
    die "Can't open dmel-all-chromosome-r6.02.fasta for reading:", $!;
}

#split the fasta record
local $/ = ">";

#scan through fasta file 
while (<FASTA>) {
    chomp;
    if ( $_ =~ /^(.*?)$(.*)$/ms) {
            my $header = $1;
            my $seq = $2;
            $seq =~ s/\R//g; # \R removes line breaks 
                    while ( $seq  =~ /([TC]C[CT]GGAAGC)/g) {
                            print $1, "\n";
            }
    }
}

更新,我已经添加了

my @matches = $seq =~ /([TC]C[CT]GGAAGC)/g;
                            print scalar @matches; 

在下面的代码中。但是,它似乎在每个模式匹配之前输出 0,而不是输出所有模式匹配的总和。

while (<FASTA>) {
    chomp;
    if ( $_ =~ /^(.*?)$(.*)$/ms) {
            my $header = $1;
            my $seq = $2;
            $seq =~ s/\R//g; # \R removes line breaks 
                    while ( $seq  =~ /([TC]C[CT]GGAAGC)/g) {
                            print $1, "\n";
                            my @matches = $seq =~ /([TC]C[CT]GGAAGC)/g;
                            print scalar @matches;
    }
    }
}

编辑:我需要输出列出找到的模式匹配。我还需要它来查找找到的匹配总数。例如:

CCTGGAAGC

TCTGGAAGC

TCCGGAAGC

找到 3 个匹配项

4

3 回答 3

3

计算每个模式匹配的出现次数

my @matches = $string =~ /pattern/g

@matches数组将包含所有匹配的部分。然后,您可以执行以下操作以获取计数。

print scalar @matches

或者你可以直接写

my $matches = () = $string =~ /pattern/

我建议您使用前者,因为您将来可能需要检查“匹配的内容”(也许是为了调试?)。

示例 1:

use strict;
use warnings;
my $string = 'John Doe John Done';
my $matches = () = $string =~ /John/g;
print $matches; #prints 2

示例 2:

use strict;
use warnings;
my $string = 'John Doe John Done';
my @matches = $string =~ /John/g;
print "@matches"; #prints John John
print scalar @matches; #prints 2

编辑:

while ( my @matches = $seq  =~ /([TC]C[CT]GGAAGC)/g) {
    print $1, "\n";
    print "Count of matches:". scalar @matches;
}
于 2016-10-20T13:07:52.253 回答
2

当您编写代码时,您必须自己计算匹配项:

local $/ = ">";
my $count = 0;

#scan through fasta file 
while (<FASTA>) {
    chomp;
    if ( $_ =~ /^(.*?)$(.*)$/ms) {
            my $header = $1;
            my $seq = $2;
            $seq =~ s/\R//g; # \R removes line breaks 
                    while ( $seq  =~ /([TC]C[CT]GGAAGC)/g) {
                            print $1, "\n";
                            $count = $count +1;
            }
    }
}
print "Fount $count matches\n";

应该做的工作。

HTH乔治

于 2016-10-20T15:55:15.467 回答
1
my @count = ($seq  =~ /([TC]C[CT]GGAAGC)/g);
print scalar @count ;
于 2016-10-20T13:12:35.227 回答