2013-04-03 65 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 //; }'。 –

相關問題