Alexandr
Alexandr

Reputation: 99

Perl: how to remove all after first blank line?

I have some string and i need remove all after first blank line in this string.

i tried use this $string = ~s/\^\s*$.*// but this expression delete all characters in string!

Upvotes: 0

Views: 626

Answers (1)

Miller
Miller

Reputation: 35198

Use the following:

  • \h to match horizontal spacing,
  • \n to match a newline
  • /m Modifier to allow ^ to match on any line
  • /s Modifier so the any character will match newlines

As demonstrated:

use strict;
use warnings;

my $string = do {local $/; <DATA>};

$string =~ s/^\h*\n.*//ms;

print $string;

__DATA__
Hello World
Second Line

New Paragraph
another line
final line

Outputs:

Hello World
Second Line

Addendum

To separate a header from body, just use split.

Technically, the pattern should just be /\n\n/, but given context of your question, I'd recommend:

my ($header, $body) = split /\n\h*\n/, $string, 2;

Upvotes: 4

Related Questions