How to replace spaces with underscores using perl -pe?
Question
How to replace spaces with underscores using perl -pe?
How to Replace Spaces with Underscores Using perl -pe
The perl -pe command is a powerful and concise tool to apply text transformations to each line of input, printing the result automatically. Here’s a quick refresher:
-pwraps your code in a loop that reads each line into$_, applies the code, then prints$_.-eallows you to provide Perl code directly on the command line.
To replace spaces with underscores on input lines, the substitution s/ /_/g or transliteration tr/ /_/ operators are perfect. Transliteration tends to be faster but only works for single-character replacements.
Correct Command-Line Example
Note: The error you encountered arises from trying to run a shell pipeline directly in Perl, which isn't valid Perl syntax. Instead, run the shell command in your OS shell like this:
echo "This is a test" | perl -pe 's/ /_/g'
Or equivalently:
echo "This is a test" | perl -pe 'tr/ /_/'
This outputs:
This_is_a_test
Self-contained Perl Script Example
If you want a standalone Perl script that reads from STDIN, replaces spaces with underscores, and prints the result (like perl -pe does), here is a runnable example you can test by piping input into it:
#!/usr/bin/perl
use strict;
use warnings;
while (<>) { # Read line by line from STDIN
s/ /_/g; # Replace all spaces with underscores in $_
print $_; # Print the modified line
}
Run this script and provide input like:
echo "Perl is fun" | perl script.pl
Output:
Perl_is_fun
Perl Concepts Highlighted
- Default variable
$_: Most Perl one-liners, including-pe, operate implicitly on$_, the current line buffer. - Substitution
s///vs. transliterationtr///:s///is regex-based and more flexible, whereastr///is faster for simple character replacements. -pvs-n:-pauto-prints $_, while-nonly loops without printing.
Common Pitfalls
- Attempting to run shell commands (like
echo) inside Perl code will cause syntax errors. Use shell to pipe input or read from files/STDIN within Perl. - Using substitution without the
gmodifier will only change the first space per line. - Transliteration
tr///does not accept modifiers and replaces single characters directly.
In summary, use perl -pe 's/ /_/g' or perl -pe 'tr/ /_/' on the command line, or the equivalent Perl script shown above for safe, straightforward space-to-underscore substitution.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 13ms
(empty)(empty)