Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

How do I split a file into an array using blank lines as delimiter

by aaAzhyd (Initiate)
on Dec 18, 2000 at 22:33 UTC ( #47236=perlquestion: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://47236]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2021-04-20 04:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?