【问题标题】:Perl read subsection inside open file handlePerl读取打开文件句柄内的小节
【发布时间】:2017-08-18 14:01:59
【问题描述】:

我打开了一个文件:

open (FH, "<".$File::Find::name) or die "cannot open file \"".$File::Find::name." \"!";
while (<FH>) {
  ...my code...  
}

我使用正则表达式解析行以获取我想要的数据。 现在我想读取文件的一个小节,直到在我的 while 循环中看到该小节的结尾。 即:逐行从“StartSection”读取到“EndSection”:

open (FH, "<".$File::Find::name) or die "cannot open file 
\"".$File::Find::name." \"!";
while (<FH>) {
  ...my code...
  if (/^StartSection$/) {
    while (<FH> !~ /^EndSection) {
      ... more code....
    }
  }
}

我必须如何在 Perl 中正确编程?

【问题讨论】:

  • 单词是“Perl”和“文件句柄”,而不是“PERL”和“FileHandler”。
  • 更好用open my $fh, '&lt;', $filename ...

标签: perl filehandle


【解决方案1】:

我可以想到几种方法来回答这个问题,但我会选择flip-flop operator 答案:

while (<FH>) {
   if (/^StartSection$/ .. /^EndSection/) {
       ... special code ...
   } else {
       ... regular code ...
   }
}

【讨论】:

  • 代码如何读取 if 部分中 的下一行?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多