Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Subroutines in a regex?

by heidkamp (Initiate)
on Apr 04, 2001 at 19:04 UTC ( [id://69688]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://69688]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-04-19 06:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found