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

This is a newbie question, so bear with me. I am processing a text file that has a lot of blank lines. I want Perl to skip those lines. How do I do that? I thought the following might work:

next if ($line =~ /\s+/);

However, even a sentence has whitespace between the words!

Replies are listed 'Best First'.
Re: regexp for blank lines
by davido (Cardinal) on Dec 14, 2004 at 05:56 UTC

    By blank, do you mean completely empty (except for the final \n)? Or do you mean empty except for whitespace?

    # completely empty except for trailing newline... next if $line eq "\n"; # Any amount of whitespace permitted.... next if $line =~ /^\s+$/;

    HTH


    Dave

Re: regexp for blank lines
by slloyd (Hermit) on Dec 14, 2004 at 06:06 UTC
    #strip off carriage returns $line=~s/[\r\n]+$//s; #next if the length of $line is zero next if length($line)==0;
      $line=~s/[\r\n]+$//s;

      To nitpick, the /s modifier above is meaningless; the only effect of /s is to change whether the . (dot) metacharacter matches newline or not. If a pattern does not contain a dot, then /s is meaningless, by definition. See also Re: S And M -- modifiers, that is....

Re: regexp for blank lines
by qq (Hermit) on Dec 14, 2004 at 09:37 UTC

    Your regex matches one or more whitespace, so it should match the whitespace between words. Changing it to /^\s+$/ anchors it at the start and end of the line, which works. Or you can use:

    next unless $line =~ /\S/;

    "next unless the line contains a non-whitespace character"

    qq

Re: regexp for blank lines
by prasadbabu (Prior) on Dec 14, 2004 at 06:51 UTC

    If you have undef $/

    @arr = split /\n/, $line; map {s/^\n+//;} @arr; $"="\n"; print "@arr"

    if you are using while without undef $/, try the following

    while ($line = <FILE>) { $line =~ s/^\n+//; }
    the above codes not tested, try it out if it helps you

    Prasad