Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process a multiline string line at a time

Tags:

string

perl

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?

like image 849
Vlad Vivdovitch Avatar asked May 24 '11 13:05

Vlad Vivdovitch


2 Answers

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;
  }
}
like image 174
mamboking Avatar answered Nov 11 '22 14:11

mamboking


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> ) {
    ...
like image 33
ysth Avatar answered Nov 11 '22 15:11

ysth