in reply to Re^2: ??{ } oddity
in thread ??{ } oddity

A regex is a double-quote-ish expression, so variables are interpolated, including dereferencing references. Any block of code can be stuck in place of a reference (it should return a reference, in order to dereference properly). So you can execute any code you want within a regex or a string. The result of the block will be dereferenced and interpolated into the string (here I return a ref to an empty string, so the pattern isn't changed):

It will be executed each time the regex is looked at (compiled), even if the match doesn't get that far. For example:

for (qw{dog pig cat horse}) { /.o${print "$_ gets printed\n";\''}/ and print "$_ matched\n"; } __END__ dog gets printed dog matched pig gets printed cat gets printed horse gets printed horse matched
Contrast that with (?{}), which executes arbitrary code if the expression matched up to that point (and does not insert anything into your pattern):
for (qw{dog pig cat horse}) { /.o(?{print "$_ gets printed\n"})/ and print "$_ matched\n"; } __END__ dog gets printed dog matched horse gets printed horse matched
And finally (??{}), which acts the same, but does insert into your pattern:
for (qw{dog pig cat horse}) { /.o(??{print "$_ gets printed\n"; 'g'})/ and print "$_ matched\n"; } __END__ dog gets printed dog matched horse gets printed
The latter two are "experimental" features, but ref interpolation is not.

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^4: ??{ } oddity
by insaniac (Friar) on Apr 28, 2005 at 17:09 UTC
    yeah, i needed the insert one ;-)
    thanks for the explanation of the differences..

    to ask a question is a moment of shame
    to remain ignorant is a lifelong shame