in reply to Re: Regex stored in a scalar
in thread Regex stored in a scalar

$_ = 'foo'; $left = '(.)(.)'; $right = '$1$2$2$1'; s{$left}{"qq{$right}"}ee; print "$_\n"; s{$left}{eval "qq{$right}"}e; print "$_\n"; __END__ foofo foofofo

first /e turns "" into a string qq{$1$2$2$1}

second /e interpolates qq{$1$2$2$1} at the correct time and substitutes into the original string

string eval is eval so arbitrary code could be executed

So, to make it safer, instead of eval ... use some form of String::Interpolate/String::Interpolate::RE

Replies are listed 'Best First'.
Re^3: Regex stored in a scalar ( s///eeval )
by Athanasius (Archbishop) on Aug 23, 2015 at 03:52 UTC

    Thanks Anonymous Monk and AnomalousMonk,

    So, the technique is to doubly double-stringify the RHS before doubly evaluating it! Analogous to the trick of using @{ [...] } to interpolate a function-returned list into a string.

    I like String::Interpolate (the module, not its documentation!):

    #! perl use strict; use warnings; use String::Interpolate qw( interpolate ); my $c = q{asdfghjk}; my @regex = ( { lh => q{(gh)}, rh => q{__$1__}, }, { lh => q{(h_)}, rh => q{_h!$1!}, }, ); print q{Original: }, $c, "\n"; for my $i (0 .. $#regex) { $c =~ s/ $regex[$i]{lh} / interpolate($regex[$i]{rh}) /ex; } print q{Final: }, $c, "\n";

    Output:

    13:37 >perl 1352_SoPW.pl Original: asdfghjk Final: asdf__g_h!h_!_jk 13:37 >

    Cheers,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,