Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

can substitution operator replace text with value returned from function?

by redss (Monk)
on Jun 11, 2018 at 16:34 UTC ( #1216405=perlquestion: print w/replies, xml ) Need Help??
redss has asked for the wisdom of the Perl Monks concerning the following question:

Is there a way to use the return value of the function in the replace text of the s/// operator?

In other words is there a way to effectively do this:

s/__AMOUNT__/format_number($amount)/g;
instead of this (which requires an extra line and variable):
$formatted_amount = format_number($amount);
s/__AMOUNT__/$formatted_amount/g;
  • Comment on can substitution operator replace text with value returned from function?

Replies are listed 'Best First'.
Re: can substitution operator replace text with value returned from function?
by Paladin (Priest) on Jun 11, 2018 at 16:56 UTC
    You can use the  /e modifier to  s/// to execute the RHS and use the return value as the substitution value.
    s/__AMOUNT__/format_number($amount)/eg;
Re: can substitution operator replace text with value returned from function?
by choroba (Bishop) on Jun 11, 2018 at 17:01 UTC
    That's why the /e modifier exists. It interprets the replacement part as code and uses the returned value as the substitution. You might need to capture something in the regex and use the corresponding capture group in the replacement code:
    print "42" =~ s/([0-9]+)/sprintf '%06.2f', $1/re
    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1216405]
Approved by Marshall
Front-paged by haukex
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2018-09-24 18:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Eventually, "covfefe" will come to mean:













    Results (192 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!