2012-07-19 38 views
3

我想从一个文本文件,这样提取每一行的第一个完整的数字:使用正则表达式在下面的代码Perl的正则表达式跳过每隔一行

8 gcaggcaaactgcgataataaaaggctgtttcaacagcggagtggattgt 1.5307684822361e-176 
11 tttacccagtgagtttgaagcaaggatcttttagtttaccgaaaaatgag 3.22210306380202e-293 
14 agcaatagcgcgaacagacaacctcatcagtctaccgcgcaccctttccc 1.32107737963584e-52 
20 agtgacagggaaaggcgatcgcggctttacgatcagagatcggtgtcggt 0.942504155078175 
30 tccggagactttcgattgcatgcaattcaccatcataccctcttgccctc 0 
45 actgagcccctgacgctggccagtgtagcgctgtgaagtcccctctcagg 9.49147409471272e-307 
53 gaaccgagcgatcgctgctgccattgtctcgccttctgccgaggaatgcc 2.15850303270505e-28 

my $id = undef; 
while (my $line = <INFILE>){ 
    chomp $line; 
    if ($line =~ /\A([0-9]+)/){ 
     $id = $1; 
    } 
print OUTFILE "$id\n"; 
$line = <INFILE>; 
chomp $line; 
} 

我得到的输出只包括隔行:

8 
14 
30 
53 

我试过打印出每一行都没有做匹配,一切都在那里。一旦我添加正则表达式,它会跳过其他所有行。任何想法为什么这样做?

+0

我不是Perl的familair,但不是更容易使用正则表达式中的多行标志吗? – 2012-07-19 16:00:13

回答

4

您正在从INFILE处理中读取两次,一次处于while状态,并且一次处于循环结束处。

删除,最后读:

my $id = undef; 
while (my $line = <INFILE>){ 
    chomp $line; 
    if ($line =~ /\A([0-9]+)/){ 
     $id = $1; 
    } 
    print OUTFILE "$id\n"; 
} 
+0

谢谢。我刚刚意识到我的错误是多么的明显。 – RossCampbell 2012-07-19 17:31:17

+0

呃...只有当你几个小时没有盯着它时才显而易见:o) – Dancrumb 2012-07-19 18:15:32

1

你跳过文件行

while (my $line = <INFILE>) { # Reading line once 
     chomp $line; 
     if ($line =~ /\A([0-9]+)/){  
      $id = $1; 
     } 
     print OUTFILE "$id\n"; 
     $line = <INFILE>; # Reading line again!!!!! 

    } 

,因为你在呼唤

$line = <INFILE>; 

两次。您的代码中不需要第二个$line = <INFILE>