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

Re^3: Regexp substitution using variables

by LanX (Saint)
on Nov 26, 2020 at 10:53 UTC ( [id://11124257]=note: print w/replies, xml ) Need Help??


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

> ... e.g. the ability to include parenthesized sub-expressions in the "from" part and $1 back-references in the "to" part.

Honestly .... store the full real regexp in your config and eval it (or eval it into a sub to optimize execution time)

"245$a": [ { "regexp": 's/(foo|bar)/He said "$1"/' } ]

There is no way to "safely" abstract the capture-var away, it has to be compiled into the regex and this needs an eval or /ee with all connected security issues.

> but bear in mind I do need the full power of regexp substitutions,

I have the impression your JSON format is an attempt to make it language agnostic. But the "full power" means you will be stuck with Perl.

And full power means that security becomes an illusion.

DB<111> $_="abc" DB<112> s/(.)/@{[print "what? --> $1\n"]}/g what? --> a what? --> b what? --> c DB<113>

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^4: Regexp substitution using variables
by LanX (Saint) on Nov 26, 2020 at 11:51 UTC
    Though ... there is one "lighter" version to build your replacement dynamically.

    eval the replacement-string into a sub, and apply just one /e at the s///

    DB<137> $rep = '<$1>' DB<138> eval qq( sub rep { "$rep" } ) DB<139> p "abc" =~ s/(.)/rep()/rge <a><b><c> DB<140>

    This will give you more control about what is happening, since you can use B::Deparse to check the replacement string before executing it.

    Like this you have at least a chance to reject dubious code.

    DB<140> p B::Deparse->new('-q')->coderef2text(\&rep) { use feature 'current_sub', 'evalbytes', 'fc', 'postderef_qq', 'say +', 'state', 'switch', 'unicode_strings', 'unico\ de_eval'; '<' . $1 . '>'; } DB<141>

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (7)
As of 2024-03-28 11:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found