in reply to Re: Precompiling substitution regex
in thread Precompiling substitution regex

old thread but wanted to ask what
my $sub =eval "sub { s/$_->[0]/$_->[1]/$_->[2] for (\@_)}";
does and what would be different if eval was removed?

Replies are listed 'Best First'.
Re^3: Precompiling substitution regex
by AnomalousMonk (Archbishop) on Oct 14, 2015 at 09:27 UTC

    In an eval evironment in which  @_ was, e.g.,
        @_ = ('searchPattern', 'replacementString', 'regexModifiers');
    (presumably, the eval statement is called in the context of a function to which arguments were passed via @_), the eval would return a code reference equivalent to
        sub { s/searchPattern/replacementString/regexModifiers for @_ }
    which would allow one to iterate over a list of strings and do substitutions on each (non-literal!) string:

    my $x = 'some'; my $y = 'strings'; my $z = 'here'; $sub->($x, $y, $z);

    The only benefit that I can see of using the string eval is that the regex | substitution operator modifiers  /g /e /r and perhaps a couple others cannot be "passed" in any other way. If not for these modifiers, one could simply write something like (again, assuming this is in a function in which  @_ held search/replace strings)
        my $sub = sub { s/$_->[0]/$_->[1]/xmsg for @_ };
        ...
        $sub->($x, $y, $z);
    (note the literal modifier group) and get the same result. In this example, the modifiers other than  /g could be passed in a string.

    Update: E.g.,

    c:\@Work\Perl\monks>perl -wMstrict -le "S('(?xmsi) foo', 'bar', 'g'); ;; sub S { my $sub = eval qq{ sub { s/$_[0]/$_[1]/$_[2] for \@_ } }; ;; my $x = 'foo'; my $y = 'Foo fOo foO'; my $z = 'FOO'; ;; $sub->($x, $y, $z); print qq{x '$x' y '$y' z '$z'}; } " x 'bar' y 'bar bar bar' z 'bar'
    And yes, this is a trick for a completely trusted environment. But then: "Trust, but verify!"


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

      Speaking of evaling substitution into existence, if you trust the OP to specify the regex and substitution string, and you're not validating those strings

      you might as well switch the interface/api to needing subs , so the user specifies the whole sub instead of parts to build one

      on the other hand, String::Interpolate/String::Interpolate::RE

Re^3: Precompiling substitution regex
by Anonymous Monk on Oct 14, 2015 at 06:40 UTC
    what do you observe happening when you remove eval?