String 使用tr///运算符对字符串中的字母进行计数
我想计算序列或字符串中A、C和G的数量。我已经编写了以下代码 但当我打印值时,只打印A。C和G显示为零。 在下面的代码中,我首先计算A,但是如果我通过先计算C来切换顺序,我得到C的值,但是现在A和G被打印为零 谁能告诉我我的代码有什么问题吗?谢谢String 使用tr///运算符对字符串中的字母进行计数,string,perl,count,String,Perl,Count,我想计算序列或字符串中A、C和G的数量。我已经编写了以下代码 但当我打印值时,只打印A。C和G显示为零。 在下面的代码中,我首先计算A,但是如果我通过先计算C来切换顺序,我得到C的值,但是现在A和G被打印为零 谁能告诉我我的代码有什么问题吗?谢谢 #! /usr/bin/perl use strict; use warnings; open(IN, "200BP_junctions_fasta.faa") or die "Cannot open the file: $!\n"; while(
#! /usr/bin/perl
use strict;
use warnings;
open(IN, "200BP_junctions_fasta.faa") or die "Cannot open the file: $!\n";
while(<IN>)
next if $_ =~ /\>/;
my $a = ($_ = tr/A//);
my $c = ($_ = tr/C//);
my $g = ($_ = tr/G//);
print "A:$a, C:$c, G:$g\n";
}
将您的
$\=tr/
更改为$\=~tr/
。另外,您的在时缺少一个大括号,因为'5'
中没有任何'C'
或'G'
s。您正在将$\u
的翻译值分配给$\u
。如果将($\u=~ tr/
)操作绑定到$\u
,将得到所需的结果
但是您确实不需要绑定到上下文变量。绑定是为了可以将正则表达式或转换操作应用于另一个变量。你最好写下:
my $a = tr/A//;
my $c = tr/C//;
my $g = tr/G//;
但你也可以这样做:
$_{$_}++ foreach m/[ACG]/g;
say "A:$_{A}, C:$_{C}, G:$_{G}";
open(在“input”中)或die“无法打开文件:$!\n”;
while(){
下一步如果$\=~/\>/;
我的$a={[m/(a)/g]};
我的$c={[m/(c)/g]};
我的$g={[m/(D)/g]};
打印“A:$A,C:$C,G:$G\n”;
}
回答您需要绑定运算符,=~
而不是赋值运算符0r,=
,或者您不需要绑定默认变量
最近,我一直在使用printf
来处理这类事情:
while( <DATA> ) {
next if /\>/;
printf "A:%s C:%s G:%s\n", tr/A//, tr/C//, tr/G//;
}
请注意,如果我在中使用了中的默认变量,而中使用了$\ucode>时,我会有一个冲突的额外麻烦。我知道我可以做一个评估
,但这不仅仅是一个麻烦,而且:
while( my $line = <DATA> ) {
next if $line =~ /\>/;
print "Line is $_\n";
printf "A:%s C:%s G:%s\n", map { eval "\$line =~ tr/$_//" } qw(A C G);
}
如果您不喜欢tr///
,可能有一些聪明的方法来实现XOR字符串,但我从未花足够长的时间来研究它(并不是说它会比您已经在做的更好)。谢谢。那是个新手犯的错误。
while( <DATA> ) {
next if /\>/;
printf "A:%s C:%s G:%s\n", tr/A//, tr/C//, tr/G//;
}
while( my $line = <DATA> ) {
next if $line =~ /\>/;
print "Line is $_\n";
printf "A:%s C:%s G:%s\n", map { $line =~ tr/$_// } qw(A C G);
}
while( my $line = <DATA> ) {
next if $line =~ /\>/;
print "Line is $_\n";
printf "A:%s C:%s G:%s\n", map { eval "\$line =~ tr/$_//" } qw(A C G);
}
while( my $line = <DATA> ) {
next if $line =~ /\>/;
print "Line is $line\n";
printf "A:%s C:%s G:%s\n", map { count_bases( $line, $_ ) } qw(A C G);
}
sub count_bases { eval "\$_[0] =~ tr/$_[1]//" }