根据序列ID

时间:2018-05-14 07:03:33

标签: perl fasta

我有两个文件。 seq.fasta由FASTA序列组成,ids.txt包含要从seq.fasta提取的序列的ID

例如

seq.fasta

>AUP4056.1
MFKSLIQFFKSKSNTSNIKKENAVQRQERQDIEGWITPYSGQELLNTELRQHHLGLLWQQVSMTREMFEH
LYQKPIERYAEMVQLLPASESHHHSHLGGMLDHGLEVISFAAKLRQNYVLPLNAAPEDQAKQKDAWTAAV
IYLALVHDIGKSIVDIEIQLQDGKRWLAWHGIPTLPYKFRYIKQRDYELHPVLGGFIANQLIAKETFDWL
ATYPEVFSALMYAMAGHYDKANVLAEIVQKADQNSVALALGGDITKLVQKPVISFAKQLI`
>XIM5213
FKISSKGPGDGWLTEDGLWLMSKTTADQIRAYLMGQGISVPSDNRKLFDEMQAHRVIESTSEGNAIWYCQ
LSADAGWKPKDKFSLLRIKPEVIWDNIDDRPELFAGTICVVEKENEAEEKISNTVNEVQDTVPINKKENI
ELTSNLQEENTALQSLNPSQNPEVVVENCDNNSVDFLLNMFSDNNEQQVMNIPSADAEAGTTMILKSEPE
NLNTHIEVEANAIPKLPTNDDTHLKSEGQKFVDWLKD
>bcna2598.1
GPGDGWLTEDGLWLMSKTTADQIRAYLMGQGISVPSDNRKLFDEMQAHRVIESTSEGNAIWYCQ
LSADAGWKPKDKFSLLRIKPEVIWDNIDDRPELFAGTICVVEKENEAEEKISNTVNEVQDTVPINKKENI
ELTSNLQEENTALQSLNPSQNPEVVVENCLPTNDDTHLKSEGQK

ids.txt

AUP4056.1 bcna2598.1 YUP42568 CAD42579.3 
JIK6023.5 ZNB708645

我尝试了以下程序作为答案 How to extract FASTA sequences from a file using sequence IDs in a different file? 但它只是将seq.fasta文件复制到输出。

Perl代码

#!/usr/bin/env perl

use strict;
use warnings;

open ( my $id_file, '<', 'ids.txt' ) or die $!;
#use split here, to split any lines on whitespace. 
chomp ( my @ids = map { split } <$id_file> );
close ( $id_file );

my %sequences;

open ( my $input, '<', 'seq.fasta' ) or die $!;

{
   local $/ = '';    #paragraph mode; Read until blank line

   while ( <$input> ) {
      my ( $id, $sequence ) = m/>\s*(\S+)\n(.*)/ms;
      $sequences{$id} = $sequence;
   }
}

foreach my $id ( @ids ) {

   if ( $sequences{$id} ) {
      print ">$id\n";
      print "$sequences{$id}\n";
   }
}

close ($input);
exit;

有人可以告诉我哪里出错了吗?

更新

我想将输出存储在单独的文件中。

1 个答案:

答案 0 :(得分:0)

您使用的代码适用于序列之间有空行的FASTA文件。你的不是这样失败

这应该可以正常工作,虽然我无法测试它

use strict;
use warnings 'all';

my %ids = do {
    open my $fh, '<', 'ids.txt'
            or die qq{Unable to open "ids.txt" for input: $!};
    local $/;
    map { $_ => undef } split ' ', <$fh>;
};

open my $fh, '<', 'seq.fasta'
        or die qq{Unable to open "seq.fasta" for input: $!};

my $print;
while ( <$fh> ) {
    $print = exists $ids{$1} if /^>(\S+)/;
    print if $print;
}