mosh has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I would like to search for 2 blank lines in a file by perl Reg Ex. How do I do that ? Something like: $line =~/\n\n/s ; # didn't work well. Thanks in advance. Mosh.

Replies are listed 'Best First'.
Re: search for blank lines by RegEx
by ikegami (Patriarch) on Sep 07, 2004 at 07:53 UTC

    I suspect $line only holds one line, so that what's preventing the regexp you presented from working.

    Someone recently asked a similar question. You can check out our answers in this thread.

Re: search for blank lines by RegEx
by robharper (Pilgrim) on Sep 07, 2004 at 08:20 UTC

    My naiive approach (I'm a newbie) would be to check two lines in a row, something like...

    my $prev; while (<DATA>) { if (/^\s*$/ && $prev =~ /^\s*$/) { # Two blank lines in a row found } $prev = $_; }

    It doesn't look a particularly Perl way to do it though, so I guess my inexperience is showing.

      For processing a huge file, this is a lot more (memory-) efficient than trying to load the complete file into memory. So I don't think this is a bad way to do it.

      Arjen

        The question asked for a regex solution. If you want to deviate and use a loop, there's no need to use a couple of regexes inside the loop. Something like (untested):
        perl -lne 'die "Line ", $.-2, "\n" if ($e = length() ? 0 : $e+1) == 2'
Re: search for blank lines by RegEx
by Happy-the-monk (Canon) on Sep 07, 2004 at 08:01 UTC

    given the linebreaks aren't anything funnier than \n,
    m/\n/s should match all the line breaks,
    m/\n\n/s would just match all the empty lines, but
    m/\n\n\n/s should match all ocurrencies of two empty lines. So should
    m/\n{3}/s

    Cheers, Sören

Re: search for blank lines by RegEx
by borisz (Canon) on Sep 07, 2004 at 08:14 UTC
    I suspect that you $line did not hold the whole data.
    local $/; $_ = <STDIN>; my $blanks = () =~ /\n\n+/sg; print "double lines found ( $blanks )\n";
    The example search for lines with two or more \n.
    Boris
Re: search for blank lines by RegEx
by ysth (Canon) on Sep 07, 2004 at 08:21 UTC
    Not an answer to your question (what is in $line, anyway?), but the only effect the //s flag has is to make . match newlines. If you don't have a . in your pattern, the //s does nothing.
Re: search for blank lines by RegEx
by Prior Nacre V (Hermit) on Sep 07, 2004 at 11:27 UTC

    If you are searching for blank lines in order to capture the data between them, then you might consider using paragraph mode. This should give you an idea of how to go about it:

    { local $/ = ''; while (<>) { print "Data block No. $.:"; foreach my $line (split /^/m) { line_func($line); } } }

    See this perl.com article which discusses paragraph mode, $/, $. and other special variables.

    Regards,

    PN5