Why does my Perl regex trigger an infinite loop?

I have code that captures “between” some text; in particular, between a foo $somewordand the following foo $someword.

However, what happens is that it gets stuck in the first “between,” and somehow the internal position of the line does not increase.

The input is a text file with new characters here and there: they are irrelevant, but make printing easier.

my $component = qr'foo (\w+?)\s*?{';

while($text =~ /$component/sg)
{
    push @baz, $1; #grab the $someword
}

my $list = join( "|", @baz);
my $re = qr/$list/; #create a list of $somewords

#Try to grab everything between the foo $somewords; 
# or if there no $foo someword, grab what left.

while($text=~/($re)(.+?)foo ($re|\z|\Z)/ms)   
#if I take out s, it doesn't repeat, but nothing gets grabbed.
{
#   print pos($text), "\n";   #this is undef...that a clue I'm certain.
    print $1, ":", $2; #prints the someword and what was grabbed.
    print "\n", '-' x 20, "\n";
}
+3
source share
1 answer

Update: Another update to work with 'foo', found inside the text you want to extract:

use strict;
use warnings;

use File::Slurp;

my $text = read_file \*DATA;

my $marker = 'foo';
my $marker_re = qr/$marker\s+\w+\s*?{/;

while ( $text =~ /$marker_re(.+?)($marker_re|\Z)/gs ) {
    print "---\n$1\n";
    pos $text -= length $2;
}

__DATA__
foo one {
one1
one2
one3

foo two
{ two1 two2
two3 two4 }

that was the second one

foo three { 3
foo 3 foo 3
foo 3
foo foo

foo four{}

Output:

---

one1
one2
one3


---
 two1 two2
two3 two4}

that was the second one


---
 3
foo 3 foo 3
foo 3
foo foo


---
}
+4

Source: https://habr.com/ru/post/1715480/


All Articles