Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^2: Regexp substitution using variables

by Bod (Parson)
on Nov 26, 2020 at 01:11 UTC ( [id://11124245]=note: print w/replies, xml ) Need Help??


in reply to Re: Regexp substitution using variables
in thread Regexp substitution using variables

It's working, and crucially supports back-references

That's interesting as I cannot get this to support back-references...this is very similar to my initial attempt. So I have attempted to replicate it:

use strict; my $pattern = '(testing)'; my $replacement = 'New \1'; my $flags = 'i'; my $value = 'My Testing Text'; $replacement =~ s/\\/\\\\/g; eval "\$value =~ s/$pattern/$replacement/$flags"; print "$value\n";
This prints
My New \1 Text
It doesn't substitute the capture.

Replies are listed 'Best First'.
Re^3: Regexp substitution using variables (updated)
by AnomalousMonk (Archbishop) on Nov 26, 2020 at 03:19 UTC

    The OPed sort of problem is tricky, but for this specific iteration:

    Win8 Strawberry 5.8.9.5 (32) Wed 11/25/2020 22:12:13 C:\@Work\Perl\monks >perl use strict; use warnings; my $pattern = '(testing)'; my $replacement = 'New \U$1'; my $flags = 'i'; my $value = 'My Testing Text'; ### $replacement =~ s/\\/\\\\/g; print "replacement '$replacement' \n"; eval "\$value =~ s/$pattern/$replacement/$flags"; print "$value\n"; ^Z replacement 'New \U$1' My New TESTING Text
    (An escaped backreference \1 is not kosher in a replacement string anyway; it should be in $1 form.)

    Update: Here's a version of the example code that better illustrates the process of building the evaluation string:

    Win8 Strawberry 5.8.9.5 (32) Wed 11/25/2020 22:45:44 C:\@Work\Perl\monks >perl use strict; use warnings; my $pattern = '(testing)'; my $replacement = 'New \U$1'; my $flags = 'i'; my $value = 'My Testing Text'; print "replacement '$replacement' \n"; my $eval_string = "\$value =~ s/$pattern/$replacement/$flags"; print "eval_string '$eval_string' \n"; eval $eval_string; print "$value\n"; ^Z replacement 'New \U$1' eval_string '$value =~ s/(testing)/New \U$1/i' My New TESTING Text


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (1)
As of 2024-04-25 01:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found