in reply to Subroutine Reference in a Regexp?

That'd be (??{ code }) - live demo of the following (requires a modern browser; don't mind the "Subroutine redefined" warnings, I'll have to get around to fixing those):

use warnings; use strict; my $string = "more than one part\nanother sentence more than"; sub getone { qr/more/ } sub gettwo { qr/than/ } while ( $string =~ m{( (??{getone}) \s+ (??{gettwo}) )}xg ) { print "<$1>\n"; }

Replies are listed 'Best First'.
Re^2: Subroutine Reference in a Regexp?
by Eily (Monsignor) on Nov 09, 2018 at 16:59 UTC

    I don't know how to check that but doesn't that stringify then recompile the precompiled regexes?

      I don't know how to check that but doesn't that stringify then recompile the precompiled regexes?

      Hm, that's a good question, I'm not sure at the moment how to check either... hopefully inspiration will strike later :-)

      Your and jwkrahn's posts did remind me of a possibly important caveat: (??{...}) will re-execute the block of code every time, while interpolation will only execute it once:

      use warnings; use strict; #use re 'debug'; my $str = "foobar"; sub getit { print "Getit! pos=",pos($str)//"undef","\n"; return qr/[aeiou]/i; } print "### haukex\n"; print "Matches: <", $str=~/(??{getit})/g, ">\n"; print "### jwkrahn\n"; my $reg_str = getit(); print "Matches: <", $str=~/$reg_str/g, ">\n"; print "### Eily\n"; print "Matches: <", $str=~/@{[getit]}/g, ">\n"; __END__ ### haukex Getit! pos=0 Getit! pos=1 Getit! pos=2 Getit! pos=3 Getit! pos=4 Getit! pos=5 Getit! pos=6 Matches: <ooa> ### jwkrahn Getit! pos=undef Matches: <ooa> ### Eily Getit! pos=undef Matches: <ooa>
Re^2: Subroutine Reference in a Regexp?
by Amblikai (Scribe) on Nov 08, 2018 at 20:39 UTC

    Perl never ceases to amaze me!

    Thank you!