Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks!

Is it possible to use perl subroutines inside regexp, using backreferences as parameters? Something like this

sub test{ my $value=shift; print $value; return 'la-la-la' ; } my $str = 'Hello _world_'; $str =~ s/_(.*?)_/&test(\1)/g;
I want to get 'Hello la-la-la' in $str, by get Hello &test(world).

May be I've got XY problem? I want to use in templates in my web-framework something like

.... <body> ... {_SomeModule_} </body> ...
So, the output of SomeModule should be substituted in template. So, if I want to write something like s/{_(.*?)_}/&call_module(\1)/g

Thanks, Alex.

Replies are listed 'Best First'.
Re: Call subroutines inside regexp, using backrefences as parameters
by moritz (Cardinal) on Mar 31, 2010 at 12:42 UTC
    Sure, with the /e modifier: $str =~ s/_(.*?)_/test($1)/eg;

    See perlop for details. Also note that $1 should be used instead of \1 in the substitution part of a regex.

    Update: oops, missed the actual /e in the example - bellaire++

    Perl 6 - links to (nearly) everything that is Perl 6.
      Thank you!
Re: Call subroutines inside regexp, using backrefences as parameters
by JavaFan (Canon) on Mar 31, 2010 at 14:37 UTC
    Is it possible to use perl subroutines inside regexp, using backreferences as parameters?
    Yes, and yes. But that's not what you actually want. Or do. You're using a subroutine call in the replacement part, which isn't a regexp.

    And how to do that was already explained by moritz, nothing to add to his answer.