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? so I end up with

array1:

A1 2 3 4 5
B 1 2 4
B 7 8 9

array2:

A6 7 8 9
B 1 2 3
B 5 6 7

etc.

Many thanks.

Answers


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
>>

Need Your Help

External linking and cakephp's routing engine (multilingual)

php cakephp internationalization routing multilingual

I recently build a tiny routing 'extension', that calls the routes from a MySQL table (structure downwards). I think it's worth to be mentioned, that this page runs in multiple languages (German and

Placing Text and Image Next to Each Other in Div - CSS

html css3 wrapper image

I'm trying to place a piece of text right next to an image inside a wrapper div, but all of my attempts have failed so far, and has resulted in me using an image to accomplish what I'm trying to do...