Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Side effects of (??{CODE}) in Regex (Rubber Ducking)

by LanX (Saint)
on Apr 18, 2026 at 19:00 UTC ( [id://11167584]=perlmeditation: print w/replies, xml ) Need Help??

I wanted to test the effect of the /o modifier on embedded code (context), and was very surprised about the second version using (??{CODE})

(FWIW adding /o makes the first output disappear -like expected- while the second one stays unchanged)

use v5.12; use warnings; say "-"x10, ' ?'; for my $i (1..3) { say "Match $i" if '2' =~ m/(?{say "in $i"})$i/; } say "-"x10, ' ??'; for my $i (1..3) { say "Match $i" if '2' =~ m/(??{say "in $i";$i})/; }

# This is perl 5, version 40, subversion 3 (v5.40.3) built for aarch64 +-android Compilation started at Sat Apr 18 20:38:08 perl tst_re.pl ---------- ? in 2 Match 2 ---------- ?? in 1 in 1 in 2 Match 2 in 3 in 3 Compilation finished at Sat Apr 18 20:38:08, duration 0.03 s

After looking into the docs:

It turns out that there are no guarantees whatsoever about the execution frequency if the regex is not matching.
    The exact rules for how often (?{}) and (??{}) are executed in a pattern are unspecified, and this is even more true of (*{}). In the case of a successful match you can assume that they DWIM and will be executed in left to right order the appropriate number of times in the accepting path of the pattern as would any other meta-pattern. How non- accepting pathways and match failures affect the number of times a pattern is executed is specifically unspecified and may vary depending on what optimizations can be applied to the pattern and is likely to change from version to version

So my questions are already (kind of) answered.

I'll post it anyway in the hope that it might interest you too.

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

Update

Moved to meditation

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://11167584]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2026-05-08 12:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.