http://www.perlmonks.org?node_id=69688

heidkamp has asked for the wisdom of the Perl Monks concerning the following question: (regular expressions)

I want to replace text with the results of a subroutine, ie
s/SUM(\d*)/sum($1)/g sub sum()
using (?{CODE}) is 0 width (no replacement), and I can't get it to work in the replacement section anyway.
Any ideas?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: Subroutines in a regex?
by busunsl (Vicar) on Apr 04, 2001 at 19:06 UTC
    use
    s/SUM(\d*)/sum($1)/eg
    this will execute the subroutine.
Re: Subroutines in a regex?
by alfie (Pilgrim) on Apr 05, 2001 at 13:39 UTC
    busunsl is right, but I'd like to add another feature and DWIM[1] to your code:
    s/(SUM(\d*))/&sum($2)/eg
    For I think you want to have the SUM characters stripped off, don't you?

    [1] Do What I Mean
    --
    Alfie

      Sorry to disagree, but you don't have to put parenthesis around the whole pattern, it will be substituted anyway.
Re: Subroutines in a regex?
by kilinrax (Deacon) on Apr 04, 2001 at 19:06 UTC
    This is what the 'e' option is designed for:
    s/SUM(\d*)/sum($1)/ge

    Originally posted as a Categorized Answer.