Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable variable interpolation with the Perl substitution operator?

Tags:

regex

perl

vms

I'm trying to replace a particular line in a text file on VMS. Normally, this is a simple one-liner with Perl. But I ran into a problem when the replacement side was a symbol containing a VMS path. Here is the file and what I tried:

Contents of file1.txt:

foo
bar
baz
quux

Attempt to substitute 3rd line:

$ mysub = "disk$data1:[path.to]file.txt"
$ perl -pe "s/baz/''mysub'/" file1.txt

Yields the following output:

foo
bar
disk:[path.to]file.txt
quux

It looks like Perl was overeager and replaced the $data1 part of the path with the contents of a non-existent variable (i.e., nothing). Running with the debugger confirmed that. I didn't supply /e, so I thought Perl should just replace the text as-is. Is there a way to get Perl to do that?

(Also note that I can reproduce similar behavior at the linux command line.)

like image 205
Michael Kristofik Avatar asked Oct 01 '12 18:10

Michael Kristofik


2 Answers

With just the right mix of quotes and double quotes you can get there:

We create a tight concatenation of "string" + 'substitute symbol' + "string". The two double quoted strings contain single quotes for the substitute. Contrived... but it works.

$ perl -pe "s'baz'"'mysub'"'" file1.txt

That's a DCL level solution.

For a Perl solution, use the q() operator for a non-interpolated string and execute that. Stuff the symbol into the parens using simple DCL substitution. This is my favorite because it (almost) makes sense to me and does not get too confusing with quotes.

$ perl -pe "s/baz/q(''mysub')/e" file1.txt
like image 69
Hein Avatar answered Oct 03 '22 17:10

Hein


As ruakh discovered when reading my comment, the problem of perl interpolation can be solved by accessing the %ENV hash, rather than using a shell variable:

perl -pwe "s/baz/$ENV{mysub}/" file1.txt

Added -w because I do not believe in not using warnings even in one-liners.

like image 34
TLP Avatar answered Oct 03 '22 15:10

TLP