2016-08-13 157 views
0

我與DNA序列工作的文件,這個文件的格式是這樣的,雖然有超過一個序列:的Perl:字符串中子字符串或子字符串中

>name of sequence 
EXAMPLESEQUENCEATCGATCGATCG 

我需要能告訴我們,如果一個變量(這也是一個序列)匹配任何序列的文件中,以及它匹配序列的名稱,如果有的話,是。由於這些序列的性質,我的整個變量可能包含在文件的一行中,或者變量的一行可能是我變量的一部分。 現在我的代碼看起來是這樣的:

use warnings; 
use strict; 
my $filename = "https://stackoverflow.com/users/me/file/path/file.txt"; 
my $exampleentry = "ATCG"; 
my $returnval = "The sequence does not match any in the file"; 
open file, "<$filename" or die "Can't find file"; 
my @Name; 
my @Sequence; 
my $inx = 0; 
while (<file>){ 
    $Name[$inx] = <file>; 
    $Sequence[$inx] = <file>; 
    $indx++; 
}unless(index($Sequence[$inx], $exampleentry) != -1 || index($exampleentry, $Sequence[$inx]) != -1){ 
    $returnval = "The sequence matches: ". $Name[$inx]; 
} 
print $returnval; 

然而,即使我故意設置$條目從文件中比賽,我還是回到The sequence does not match any in the file。此外,當運行代碼時,我得到Use of uninitialized value in index at thiscode.pl line 14, <file> line 3002.以及Use of uninitialized value within @Name in concatenation (.) or string at thiscode.pl line 15, <file> line 3002.

我怎麼能執行這個搜索?

回答

1

我會認爲這個腳本的目的是確定是否$exampleentry文件file.txt任何記錄匹配。一個記錄這裏描述的DNA序列,並且對應於文件中的三個連續的線。如果變量$exampleentry與記錄的第三行相匹配,它將匹配該序列。的匹配這裏意味着要麼

  • $exampleentry$line子串,或
  • $line$exampleentry子串,

其中$line referes到該文件中的相應的行。

首先,考慮輸入文件file.txt:在您嘗試閱讀這些線方案

>name of sequence 
EXAMPLESEQUENCEATCGATCGATCG 

,使用調用readline。因此,最後一次調用readline將返回undef,因爲沒有更多行可讀。

因此,它似乎是合理的,在file.txt的最後兩行是畸形的,而正確的格式應該是:

>name of sequence 
EXAMPLESEQUENCE 
ATCGATCGATCG 

如果我現在理解錯的話,我希望這能解決你的問題:

use feature qw(say); 
use strict; 
use warnings; 

my $filename = "file.txt"; 
my $exampleentry = "ATCG"; 
my $returnval = "The sequence does not match any in the file"; 
open (my $fh, '<', $filename) or die "Can't find file: $!"; 
my @name; 
my @sequence; 
my $inx = 0; 
while (<$fh>) { 
    chomp ($name[$inx] = <$fh>); 
    chomp ($sequence[$inx] = <$fh>); 
    if (
     index($sequence[$inx], $exampleentry) != -1 
     || index($exampleentry, $sequence[$inx]) != -1 
    ) { 
     $returnval = "The sequence matches: ". $name[$inx]; 
     last; 
    } 
} 
say $returnval; 

注:

  • 我已經改變了變量名稱遵循snake_case convention。例如,可變@Name使用所有小寫作爲@name更好寫入。

  • 我更改了open()呼叫以遵循新推薦的3參數樣式,請參閱Don't Open Files in the old way以獲取更多信息。

  • 二手特徵say代替print

  • 添加的每個的readline以避免在陣列存儲換行符後chomp

+0

謝謝!對不起,在這個問題上我可憐的措詞。 –