0

I have this perl command:

# Result: o
#
echo foo | perl -pe 's/f(o)o/$1/'

I'd like the replacement expression to be passed via env variable:

echo foo | REPLACE='$1' perl -pe 's/f(o)o/$ENV{REPLACE}/'

however, in this case, Perl does not interpret the matching variable $1; instead, it just replaces it with the env variable value, so that the result is $1.

I know I can work this around via Bash string interpolation:

REPLACE='$1'
echo foo | perl -pe 's/f(o)o/'"$REPLACE"'/'

however, this is hackish (and limited).

Is the a more idiomatic Perl way to accomplish this task?

Marcus
  • 5,104
  • 2
  • 28
  • 24

2 Answers2

3

The string eval is a little insecure, but

echo foo | REPLACE='$1' perl -pe 's/f(o)o/$ENV{REPLACE}/ee'

works.

mob
  • 117,087
  • 18
  • 149
  • 283
  • Now that you've provided the related terminology, I've found a similar question: https://stackoverflow.com/q/6082219. – Marcus Nov 08 '22 at 18:51
  • Also, unlike the OP's hackish solution, this doesn't work for `REPLACE='a$1'`. That said, `REPLACE='"a$1"'` would work. – ikegami Nov 08 '22 at 19:25
1

You want to use $ENV{REPLACE} as a template. String::Substitution provides the tools to work with such templates.

perl -MString::Substitution=sub_modify \
   -pe'sub_modify( $_, qr/f(o)o/, $ENV{REPLACE} )'
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Interesting. It seems that the module required is not provided by a standard Ubuntu installation – Marcus Nov 11 '22 at 13:42