Vlad Vivdovitch
Vlad Vivdovitch

Reputation: 9815

How to process a multiline string line at a time

I'd like to get a substring between two delimiters (regexes) from a string. I want to use this:

while (<>) {
  if (/START/../END/) {
    next if /START/ || /END/;
    print;
  }
}

But this works on lines of stdin. I'd like make it work on lines of a string. How?

Upvotes: 7

Views: 11597

Answers (3)

mamboking
mamboking

Reputation: 4637

If you mean you want to process a string that already contains multiple lines then use split:

foreach (split(/\n/, $str)) {
  if (/START/../END/) {
    next if /START/ || /END/;
    print;
  }
}

Upvotes: 11

ysth
ysth

Reputation: 98378

Simply:

my ($between) = $string =~ /START(.*?)END/s;

Alternatively, read from the string:

use 5.010;
open my $string_fh, "<", \$string or die "Couldn't open in-memory file: $!";
while ( <$string_fh> ) {
    ...

Upvotes: 8

Fredrik Pihl
Fredrik Pihl

Reputation: 45634

There are many ways to get multiline data into a string. If you want it to happen automatically while reading input, you'll want to set $/ (probably to '' for paragraphs or undef for the whole file) to allow you to read more than one line at a time.

see "multiline" section @ perldoc

Upvotes: -1

Related Questions