in reply to Having scalars handled as regexs inside a substitution

You could also use eval:
sub findandreplace { my ($string, $find, $replace)=@_; eval { $string =~ s/$find/$replace/; } die "$@" if $@; $string; }

--ZZamboni

Replies are listed 'Best First'.
RE: Re: Having scalars handled as regexs inside a substitution
by DrManhattan (Chaplain) on May 20, 2000 at 19:48 UTC
    Close, but you have to avoid evaluating the first occurance of $string:
    sub findandreplace { my ($string, $find, $replace) = @_; eval '$string' . " =~ s/$find/$replace/"; $string; }

    Otherwise, you end up with the value of $string on the LHS of the =~ instead of the variable $string.
    - Matt
      No. What you say would happen if I had enclosed the eval'ed code in quotes, but because I used braces, it just uses the existing variables, but does not perform a textual substitution.

      Doing substitution with user-supplied patterns in an eval block in quotes is dangerous, because it allows the user to provide things like @{[ code ]} in the patterns, which can execute arbitrary perl code.

      --ZZamboni