http://www.perlmonks.org?node_id=47236

aaAzhyd has asked for the wisdom of the Perl Monks concerning the following question: (files)

I have a file such as:

--
blah blah blah
blah blahblahblalh

oh yeah interesteing

no no no
nonnono

yes yes
--

I am wanting to read the file into an array spliting each element
by a blank line, such as @array[0] would be:

blah blah blah
blah blahblahblalh

Here is what I have tried doing:

open (LOG,"Messages.log"); while (<LOG>){ $string .= $_; } @array = split(/^\s*$/, $string);
and i have tried messing around with the regular expresion with no luck ..

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: Spliting a file into an array using blank lines as delimiter
by davorg (Chancellor) on Dec 18, 2000 at 22:41 UTC

    The secret is to change $/ to the empty string. This will put Perl into 'paragraph mode', where the input record separator is one or more blank lines. Something like this:

    #!/usr/bin/perl -w use strict; my @array; { local $/ = ''; @array = <DATA>; } print $array[0]; __END__ blah blah blah blah blahblahblalh oh yeah interesteing no no no nonnono yes yes
Re: Spliting a file into an array using blank lines as delimiter
by dsb (Chaplain) on Jan 24, 2001 at 20:06 UTC
    your code would work but the pattern you have '$string' splitting on is no good. Right now you have it matching any line with 0 or more whitespaces at the beginning. That's every line. Try this:
    open (LOG,"Messages.log"); while (<LOG>){ $string .= $_; } @array = split(/\n{2,}/, $string); # note the new pattern