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.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.