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.

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


In reply to Side effects of (??{CODE}) in Regex (Rubber Ducking) by LanX

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.