(Unfortunately, the straightforward attempt $str =~ s/[+-](\d+).{\1}//g; doesn't work.)
How come the straight forward way doesn't work?
Because the regex compiler will attempt to compile the entire [+-](\d+).{\1} regex (the 'search' regex of the substitution) at compile time, but the \1 backreference of the .{\1} counted quantifier sub-expression is not known until run time, when something may be captured that it can actually refer back to. OTOH, the (??{".{$1}"}) 'postponed' extended pattern is specifically designed to both compile and run at run-time.
BTW: The use of $^N is, IMHO, 'safer' than the use of $1 in the sub-expression (??{ ".{$1}" }) (making it (??{ ".{$^N}" }) instead) because $^N equals the contents of the most recently closed capturing group and will not change (semantically) if the relative positional relationship between that capture group and the use of $^N does not change; whereas adding another capture group anywhere before the (\d+) group will change the semantics of $1 because capture group counting will change.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|