如何使用$ _找出perl中的下一行是否为空?

时间:2012-12-13 03:14:34

标签: perl

我有一个文本文件。

open FILE,"<data.txt";
while(<FILE>) {
  print $_;
  if($_ =~ m/Track/) {
    # do something ......
    #if next line is blank do something else....
  }
}

但如何找出答案呢?有什么想法吗?

4 个答案:

答案 0 :(得分:4)

您尚未阅读下一行,因此您无法检查它是否为空白。相反,您必须使用缓冲区,以便在遇到空行时使用较早的行。

my $last;
while (<>) {
   s/\s+\z//;
   if ($.>1 && !length) {
      ...do something with $last...
   }

   $last = $_;
}

答案 1 :(得分:2)

如果您尚未阅读下一行,则无法根据下一行的内容做出任何决定。但你可以这样做:

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;
}

当你到达文件的末尾并且没有下一行要阅读时,你还必须确定你想要做什么。

答案 2 :(得分:1)

其他一些想法,取决于你正在做的其他事情:

使用File :: ReadBackwards向后读取并跟踪“previous”行是否为空。

阅读段落模式($/ = "")并匹配/(^.*Track.*\n)(.)?/m,根据$ 2定义或不同。

使用Tie :: File将文件绑定到数组并循环索引。

答案 3 :(得分:0)

一般情况下,我喜欢在此行保存您的州的其他建议,找到符合您未来条件的行并检查过去的情况。

但是特别针对这种事情,你说的是我喜欢在文件中啜饮并使用一个表达式来找到你正在寻找的两条线。如果你最终想要使用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部分不太满意,但我试图避免使用$'$&,据说这会减慢所有匹配器的速度。如果文件不包含任何包含“Tracks”的行,我也不确定这是否有效。

我测试了这个:

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.