在 Perl 中读取文件时如何跳过行?
我该怎么做?
open FILE, $somefile;
foreach (<FILE>)
{
if (/some_regex/)
{
$want_the_next_line = <FILE>;
$want_the_next_line_after_that = <FILE>;
}
}
明白我的意思吗?我基本上想在我的 foreach 中间插入一堆行,而不是每次迭代时都必须记住我的状态并检查它.而且我目前在 Perldoc 中找不到任何关于 <> 的有用信息.
Know what I mean? I basically want to slurp in a bunch of lines in the middle of my foreach, instead of having to remember my state and check it every time I iterate through. And I currently can't find anything helpful on <> in Perldoc.
哦,顺便说一下,我真的不想:
Oh, and by the way, I really don't want to:
@file = <FILE>;
我相信你明白.
使用 while
而不是 foreach
:
open FILE, $somefile;
while (<FILE>) # <<-- HERE
{
if (/some_regex/)
{
$want_the_next_line = <FILE>;
$want_the_next_line_after_that = <FILE>;
}
}
while
循环只会从
读取一行,然后您可以在当前迭代中随心所欲地使用它.
The while
loop will only read a single line from <FILE>
and you can then do as you wish with it in the current iteration.
此外,此技术将帮助您避免一次读取整个文件.
Also this technique will help you to avoid reading the whole file at once.
技术背景: foreach()
需要一个数组,因此一次读取整个文件,而while()
中的表达式> 循环是标量上下文,只检查假"值,就像 EOF 产生的那样.
Technical background: foreach()
requires an array, therefore reading in the whole file at once, while the expression in the while()
loop is scalar context and is only checked for "false" values, like the one EOF produces.