2013-04-03 66 views
1

我在解析文本文件时如何跳过第9行?Perl:读取文件时跳过第N行

这里是我

use strict; use warnings; 
open(my $fh, '<', 'file.txt') or die $!; 
my $skip = 1; 
while (<$fh>){ 
    $_=~ s/\r//; 
    chomp; 
    next if ($skip eq 9) 
    $skip++; 
} 

不知道这是否正常工作,但我敢肯定有一个更雄辩做的。

+1

我只能假设,单曲/ \ r //'是存在的,因为你有[␍␊(HTTP:// stackoverflow.com/a/3098328/1337)终止的行。如果是这种情况,你应该用[':crlf'](http://perldoc.perl.org/functions/open.html)图层('open(my $ fh,'<:crlf', 'file.txt')') –

回答

11

您可以使用$.

use strict; use warnings; 
open(my $fh, '<', 'file.txt') or die $!; 
while (<$fh>){ 
    next if $. == 9; 
    $_=~ s/\r//; 
    chomp; 
    # process line 
} 

也可以使用$fh->input_line_number()

+1

好,所以'$ .'是一个特殊的变量,用于存储当前读取的最后一个文件句柄的输入行号。我刚刚从这个[SITE](http://www.kichwa.com/quik_ref/spec_variables.html)中读到。我直到今天才知道。谢谢 – cooldood3490

+3

@ cooldood3490要检查的正确位置是与'perl'一起安装的文档:'perldoc -v'$。'[perldoc.perl.org]上提供了当前版本的文档(http:// perldoc .perl.org/perlvar.html#%24。)我会建议远离拼写错误语言名称的网站。 –

+0

而不是'$ _ =〜s/\ r //;',写's/\ r //'。更好的是,写'while(my $ line = <$fh>){$ line =〜s/\ s + \ z //; }'。 –

相关问题