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

hi

I Tried to use a function in a replace regex but the function was considered as a dead string.
I tried something like:
$t =~ s/$somePattern/$1 becomes some_function($1)/g;

I know I can: split than map and than join,
but there's got to be a more process time friendly way,
like a way to include a function within a replace regex.

So, what do you say ?
Is there a way to do this ?

thx

Replies are listed 'Best First'.
Re: using functions within regex
by toolic (Bishop) on May 04, 2011 at 00:59 UTC
Re: using functions within regex
by davido (Cardinal) on May 04, 2011 at 03:16 UTC

    Are you looking for the /e option? (See perlre and perlretut). Here's an example, in action:

    use 5.010_001; use strict; use warnings; my $string = "It's hard to teach an old dog new tricks."; $string =~ s/(dog)/reverse($1)/e; say $string;

    The output: "It's hard to teach an old god new tricks." What's happening here is the right-hand side is being evaluated as code. The code should return a string which will serve as the replacement string.


    Dave

Re: using functions within regex
by jwkrahn (Abbot) on May 04, 2011 at 05:02 UTC
    I Tried to use a function in a replace regex

    The second half of the substitution operator (s///) is just a string, not a regex.

    One way to do it is:

    $t =~ s/$somePattern/@{[ some_function($1) ]}/g;

      That would be the perfect way, if the /e modifier wasn't specifically designed to provide a means of executing code on the RHS of the s/// operator, without jumping through that hoop.


      Dave

        Not so perfect, in any event. Here's a snippet of a debugging session

        DB<1> $t = 'teach an old dog new tricks' DB<2> $t =~ s/(dog)/@{[ reverse($1) ]}/g DB<3> x $t 0 'teach an old dog new tricks'
        You'd have to do
        $t =~ s/(dog)/@{[ scalar(reverse($1)) ]}/g