我有一個文本文件。
open FILE,"<data.txt";
while(<FILE>) {
print $_;
if($_ =~ m/Track/) {
# do something ......
#if next line is blank do something else....
}
}
但是如何找出那個?任何想法?
我有一個文本文件。
open FILE,"<data.txt";
while(<FILE>) {
print $_;
if($_ =~ m/Track/) {
# do something ......
#if next line is blank do something else....
}
}
但是如何找出那個?任何想法?
您不能根據下一行的內容作出任何決定,如果你沒有看過下一行呢。但是,你可以這樣做:
open FILE,"<data.txt";
my $current = <FILE>;
my $next;
while(<FILE>) {
$next = $_;
print $current;
if ($next) {
# do something ......
} else {
#if next line is blank do something else...
}
$current = $next;
}
你也得正是你想要當你到了文件的末尾並沒有下一行讀做什麼決定。
您還沒有閱讀下一行,因此您無法檢查它是否爲空白。相反,一旦遇到空白行,您必須使用緩衝區來讓您使用早期的行。
my $last;
while (<>) {
s/\s+\z//;
if ($.>1 && !length) {
...do something with $last...
}
$last = $_;
}
一些其他的想法,這取決於你在做什麼其他:
與文件:: ReadBackwards向後閱讀並跟蹤的「以前」行是否爲空或不。
在段落模式($/ = ""
)中閱讀並匹配/(^.*Track.*\n)(.)?/m
,根據$ 2做不同的事情被定義與否。
使用Tie :: File將文件綁定到數組並遍歷其索引。
總的來說,我喜歡其他的建議(S)以保存這條線上你的狀態,找到適合你的未來狀況的線,並檢查了過去的狀態。
然而專門爲這種事情你談論我喜歡的文件中啜和使用發現你正在尋找的兩行的表達式。如果你最終想要使用s///mg
而不是m//
;
open FILE,"<data.txt";
my $text = do { local($/) ; <FILE> } ;
close FILE;
# the slurping I mentioned is now done.
my $tail = "";
while($text =~ m/\G((?:.|\n)*?)^.*Tracks.*$/mg) {
print $1;
if($text =~ m/\G.^$/ms) {
print "the next line is blank";
} else {
print "wait,";
}
$text =~ m/(\G.*)/ms;
$tail = $1;
}
print $tail;
我不是太高興了$tail
件以上,但我試圖避免使用$'
和$&
的,據說減緩所有的匹配。另外我不確定這是否適用,如果該文件不包含任何包含「曲目」的行。
我測試這:
Hello, I am going to tell you a story about a line containing Tracks that isn't followed by a blank line though and another line containing Tracks which was And then only the one word Tracks not followed by a blank line As opposed to Tracks and that's the story.
,並得到:
Hello, I am going to tell you a story wait, that isn't followed by a blank line though the next line is blank And then only the one word wait, not followed by a blank line As opposed to the next line is blank and that's the story.
你不能告訴下一行是什麼,但你可以跟蹤的前行是什麼,然後在當前行爲空白時對其進行操作。 –
你不需要顯式匹配'$ _'。 '$ _'存在的原因是你可以使用快捷鍵'if(/ Track /){...' –