#!/usr/bin/perl $tempstr = qq` [IF a = /1/ 1 ELSIF b = /2/ 2 ELSE 3 ] `; my $reg = qr{\[(?:(?>[^\[\]]+)|(??{$reg}))*\]}; $tempstr =~ s/\[(?:IF|ELSIF|ELSE)(\s+\S+\s*\=\s*.*?)?\n((?:$reg|\n|[^\ +[\]])+\])/iffer($1,$2)/ges; sub iffer { my $test = shift; $test .= shift; print "trying iffer... test: $test\n"; my $reg = qr{\[(?:(?>[^\[\]]+)|(??{$reg}))*\]}; $test =~ s/(?:(?:$reg|\n|[^\[\]])+?)(^(?:ELSIF|ELSE\s*\n).*\]|\])/\[$1 +/sm; return $test; }

The above code runs "iffer" once and results in:

$ ./t.pl trying iffer... test: a = /1/1 ELSIF b = /2/ 2 ELSE 3 ] $

The following code, with the only difference being the inclusion of the while loop, results in a different (and desired) result:

#!/usr/bin/perl $tempstr = qq` [IF a = /1/ 1 ELSIF b = /2/ 2 ELSE 3 ] `; my $reg = qr{\[(?:(?>[^\[\]]+)|(??{$reg}))*\]}; while ($tempstr =~ s/\[(?:IF|ELSIF|ELSE)(\s+\S+\s*\=\s*.*?)?\n((?:$reg +|\n|[^\[\]])+\])/iffer($1,$2)/ges) {} sub iffer { my $test = shift; $test .= shift; print "trying iffer... test: $test\n"; my $reg = qr{\[(?:(?>[^\[\]]+)|(??{$reg}))*\]}; $test =~ s/(?:(?:$reg|\n|[^\[\]])+?)(^(?:ELSIF|ELSE\s*\n).*\]|\])/\[$1 +/sm; return $test; }

And the results:

$ ./t.pl trying iffer... test: a = /1/1 ELSIF b = /2/ 2 ELSE 3 ] trying iffer... test: b = /2/2 ELSE 3 ] trying iffer... test: 3 ] $

Can someone help me understand why these two result in two totally different results? Shouldnt the inclusion of the /g modifier in the first ensure that the pattern is matched repeatedly (i.e., the ELSIF and then ELSE patterns match)... (The complexity of the regular expressions are to account for the possibility of nested conditionals in my own "mini-language".)


In reply to Complex regex and apparent failure of /g option by lokiloki

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.