2

I have a string, with newlines and odd characters in it, like quotes, commas, backslashes etc (it can be quite long, so not simple to escape characters).

Eg

STRING_FROM_BASH="blah2 => '/blah',"

perl -0777 -i.original -pe "s/###matchingchars/$STRING_FROM_BASH/igs" myfile

I get an error

Having no space between pattern and following word is deprecated at -e line 1

Which I assume is because its interpolating the bash string.

Is there any way to make Perl not interpolate that replacement string?

Ian
  • 13,724
  • 4
  • 52
  • 75
  • 1
    The discussion and answers on https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed might be of use here. Assigning the string to a perl variable and then using that variable might also work better. – Etan Reisner Jun 23 '15 at 16:38
  • 1
    You could always just use the program arguments. But the fancier perl quoting methods can probably fairly safely quote an arbitrary string (though I don't know what those are offhand). – Etan Reisner Jun 23 '15 at 16:45
  • 1
    Can `###matchingchars` contain a newline? If not, I don't see why you used `-0777`. – ikegami Jun 23 '15 at 19:41

2 Answers2

2

Don't try to generate Perl code from the shell.

You can pass it as a command-line argument:

perl -0777 -i.original -pe '$S //= pop; s/###matchingchars/$S/igs' myfile "$STRING_FROM_BASH"

You can pass it as an environment variable:

S="$STRING_FROM_BASH" perl -0777 -i.original -pe 's/###matchingchars/$ENV{S}/igs' myfile 
ikegami
  • 367,544
  • 15
  • 269
  • 518
mpapec
  • 50,217
  • 8
  • 67
  • 127
  • Super, I had found another solution, but this works fine and feels a bit nicer, so will switch to this. – Ian Jun 23 '15 at 16:58
  • @Ian `%ENV` is actually better solution. :) – mpapec Jun 23 '15 at 16:59
  • Ok, thanks, can I just ask, where I could read about the pop thing ? – Ian Jun 23 '15 at 17:00
  • 1
    @Ian without arguments it operates on `@ARGV` or `@_` inside subroutine. http://perldoc.perl.org/functions/pop.html – mpapec Jun 23 '15 at 17:01
  • 2
    Placing the string first and using `shift` would make far more sense. It's tradition to place the opened ended list of files last. – ikegami Jun 23 '15 at 19:36
1

Thanks to Etan, I've found a workaround, I set the variable up, and then use it within Perl like the following...

replacement=STRING_FROM_BASH perl -0777 -i.original -pe 's/###matchingchars/$ENV{replacement}/igs' myfile
Ian
  • 13,724
  • 4
  • 52
  • 75