Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^2: Interpolate into replacement with s//?

by ikegami (Patriarch)
on Nov 09, 2011 at 20:43 UTC ( [id://937217]=note: print w/replies, xml ) Need Help??


in reply to Interpolate into replacement with s//?

$replace contains a template. Therefore, you need a template engine to process it. The only existing template module I know that can process that language is String::Interpolate. (Yeah, it has a weird interface.)

Alternatively, if $replace actually contained a string literal (i.e. Perl code), you could use eval to evaluate it.

$string = 'ABC'; $search = qr/^(A)/; $replace = '"$1Z"'; $string = s{$search}{ my $replacement = eval($replace); die $@ if $@; $replacement }eg; say $string;

Replies are listed 'Best First'.
Re^3: Interpolate into replacement with s//?
by tchrist (Pilgrim) on Nov 09, 2011 at 20:54 UTC
    ikegami wrote:
    $replace contains a template. Therefore, you need a template engine to process it.
    Aw /gee whiz, we don’t need no stinkin’ modules for such a trivial task. Merely render unto Perl that which is Perl’s:
    use v5.14; my $string = q/ABC/; my $search = qr/^(A)/; my $replace = q/"Z\l$1Z"/; $string =~ s/$search/$replace/gee; say $string;
    Which when run duly prints out ZaZBC.
      Hmm, I tried /gee but $replace isn't directly assigned, it's from elsewhere so say I'd read $replace from another file and it was a string 'Z$1Z' then this doesn't seem to work?

        It doesn't matter where the string came from. Notice he changed Z$1Z (not Perl code) to "Z$1Z" (Perl code). So you'd need to either change the file or add quotes to what you read from the file.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (7)
As of 2024-04-24 20:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found