http://qs321.pair.com?node_id=1216405

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 (Vicar) 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 (Cardinal) 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,