1

I want to remove whitespace between back-tick (\x60) and word characters, inside of a perl script that performs many other regex substitutions. If I print the result of the earlier substitutions to the bash shell and then pipe into a new perl invocation, it works. But inside a single perl invocation, it doesn't. In the example below, the third line (a single perl command) does not work whereas the fourth line (two separate commands) does work.

printf '%b' 'Well, `\n he said it \n' 
printf '%b' 'Well, `\n he said it \n' | perl -p -e 'use strict; use warnings; s|\n||g;' ; echo
printf '%b' 'Well, `\n he said it \n' | perl -p -e 'use strict; use warnings; s|\n||g; s|([\x60])\s*(\w)|$1$2|g;' ; echo
printf '%b' 'Well, `\n he said it \n' | perl -p -e 'use strict; use warnings; s|\n||g;' | perl -p -e 'use strict; use warnings; s|([\x60])\s*(\w)|$1$2|g;'; echo

Why does it not work inside a single perl invocation? I thought we were supposed to avoid multiple or nested pipes (subshells).

This is perl 5, version 18 and GNU bash, version 3.2.57(1) in BSD unix.

Jacob Wegelin
  • 1,304
  • 11
  • 16

1 Answers1

3

Because your perl -p is splitting on newlines, your first perl removes them, and the second one sees everything as if it were on one line.

printf '%b' 'Well, `\n he said it \n' | perl -p0 -e 'use strict; use warnings; s|\n||g; s|([\x60])\s*(\w)|$1$2|g;' ; echo

By telling perl to slurp it all in at once, the first s can remove the new lines, and the second will remove the spaces after your quote.

Tanktalus
  • 21,664
  • 5
  • 41
  • 68
  • `-0` doesn't actually enable slurp mode; use `-0777` for that. – ikegami Mar 26 '19 at 23:53
  • @Tanktalus, this is very helpful. Where are -0 and -0777 documented? How does syntax change to perform this in a perl script, rather than a command-line invocation? – Jacob Wegelin Mar 27 '19 at 01:52