在您解释的情况下,我不会使用正则表达式。相反,只需查看您已阅读的行数,并在您阅读正确的行数时输出您喜欢的任何内容:
while( <DATA> ) {
if( $. % 3 ) { # $. is the line number for that filehandle
print;
}
else {
chomp;
print $_, ",\n\n";
}
}
__DATA__
a1
a2
a3
b1
b2
b3
c1
c2
c3
如果您的内容在程序中的标量中,您可以在该标量上打开文件句柄,以便使用相同的文件读取工具:
open my $string_fh, '<', \$content;
while( <$string_fh> ) {
if( $. % 3 ) { # $. is the line number for that filehandle
print;
}
else {
chomp;
print $_, ",\n\n";
}
}
把事情变成文件读取问题是我最喜欢的技巧之一,我在Effective Perl Programming 中展示了更多的方法来做这种事情。例如,如果您还想写入字符串而不是标准输出,则可以在标量引用上打开文件句柄:
open my $string_fh, '<', \$content;
open my $out_fh, '>', \(my $out);
while( <$string_fh> ) {
if( $. % 3 ) { # $. is the line number for that filehandle
print {$out_fh} $_
}
else {
chomp;
print {$out_fh} $_, ",\n\n";
}
}
print $out;
这使得在捕获字符串中的信息或写入“真实”文件句柄之间来回切换变得很容易。