1

I'm not new to Perl, but I use it far too rarely to learn everything one needs to remember. Now I'm writing a simple script that iterates over each line of a file and makes a few changes as needed. The interesting part looks like this:

while (<>)
{
    $modified_line = ... # modify current line as required
    print $modified_line; # print out the modified line
}

This is all working fine, but I only need to apply a few changes in the beginning of the file, and I don't like the idea of iterating over every single line only for that. I would rather like to break out of the loop upon a particular condition and print out the rest of the input file unchanged. Is this possible?

while (<>)
{
    $modified_line = ... # modify current line as required
    print $modified_line; # print out the modified line
    last if /^\[.*]$/; # break out if line is enclosed in []
}
# how to print out the rest of the file unchanged here?
4

2 回答 2

4

你可以添加

print while <>;

它仍然会读取文件的所有其余部分——它必须能够将其余数据复制到输出中——但这真的不是问题。

于 2013-06-13T15:43:25.477 回答
2

无论如何,您的示例将继续。如果条件为真,您想退出,例如:

while (<>)
{
    $modified_line = ... # modify current line as required
    print $modified_line; # print out the modified line
    last if /^\[.*]$/; # break out if line is enclosed in []
}
于 2013-06-13T15:42:56.707 回答