繁体   English   中英

如何正确使用chomp命令摆脱perl中的\\ n字符?

[英]How do I use correctly chomp command to get rid of \n character in perl?

我的问题很简单:我有一个看起来像这样的数据库: 在此处输入图片说明

我的目标只是消除每个序列行末尾的换行符\\ n,而不是标题,我尝试了以下代码

#!/usr/bin/perl
use strict;
my $db = shift;
my $outfile= "Silva_chomped_for_R_fin.fasta";
my $header;
my $seq;
my $kick = ">";

open(FASTAFILE, $db);
open(OUTFILE,">". $outfile);

while(<FASTAFILE>) {
    my $currentline = $_;
    chomp $currentline;
    if ($currentline =~ m/^$kick/) {
        $header = $currentline;
    } else {
        chomp $currentline;
        $seq = $currentline;
    }
    my $path = $header.$seq."\n";
    print(OUTFILE $path);
}

close OUTFILE;
close FASTAFILE;
exit;

但是我得到的不仅仅是以下内容: 在此处输入图片说明

像如果chomp根本不起作用..任何关于我做错事的想法吗? 非常感谢Alfredo

while()循环存在三个问题。

  • 您正在循环的开头无条件地运行chomp()
  • 然后,您将在循环末尾重新添加换行符(这chomp()了先前的chomp()的用途)。
  • 您正在将标题连接到每一行。

这是一个简化的版本。

use strict;
use warnings;

my $db = shift;
my $outfile = "out.fasta";

open(my $fh, "<", $db) or die "Could not open input file";
open(my $out, ">", $outfile) or die "Could not open output file";

my $header;

while (<$fh>) {
    $header = /^>/;
    chomp unless $header;
    print $out $. > 1 && $header && "\n", $_;
}

close $out;
close $fh;

线

print $out $. > 1 && $header && "\n", $_;

将有条件前面加上一个新行的输出,如果这符合一个开始“>” - ,除非它是在该文件中的第一行。 $.变量是当前行号。)

图片来源: ikegami在我的原始代码中发现了该错误,以允许输入数据库中包含多个序列。

my $add_lf = 0;
while (<>) {
   chomp;
   if (/^>/) {
      print("\n") if $add_lf;
      print("$_\n");
      $add_lf = 0;
   } else {
      print;
      $add_lf = 1;
   }
}

print("\n") if $add_lf;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM