簡體   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