[英]How do I split a text file into blocks using Perl?
I have a data file with lines like this: 我有一个像这样的数据文件:
A1 2 3 4 5
B 1 2 4
B 7 8 9
A6 7 8 9
B 1 2 3
B 5 6 7
A3 6 9 7
B 2 3 3
B 5 6 6
Using Perl, how do I split the file into a set of arrays (or any other data structure) when the parser hits a /^A/
please? 使用Perl,当解析器命中
/^A/
时,如何将文件拆分为一组数组(或任何其他数据结构)? so I end up with 所以我最终
array1: 数组1:
A1 2 3 4 5
B 1 2 4
B 7 8 9
array2: 数组2:
A6 7 8 9
B 1 2 3
B 5 6 7
etc. 等等
Many thanks. 非常感谢。
I had to rewrite the answer (after rewritten question) 我不得不重写答案(重写问题后)
@arrays = ();
while (<>) {
push(@arrays, []) if /^A/;
push(@{$arrays[-1]}, $_)
}
It is at times like this when I wish $/
could be more than just a string. 在这种情况下,我希望
$/
可以不仅仅是一个字符串。 Nevertheless, there are workarounds. 但是,有解决方法。
One could slurp the file in and process with a lookahead assertion. 可以使用前瞻性断言来处理文件并进行处理。 The example below simply prints each string delimited with
<< >>
, but the basic idea is the same regardless of what you want to do with the data: 下面的示例仅打印每个以
<< >>
分隔的字符串,但是不管您想对数据做什么,基本思想都是相同的:
$ perl -0777 -wE 'say "<<$_>>" for split /(?=^A)/m, <>' file.txt
<<A1 2 3 4 5
B 1 2 4
B 7 8 9
>>
<<A6 7 8 9
B 1 2 3
B 5 6 7
>>
<<A3 6 9 7
B 2 3 3
B 5 6 6
>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.