one-liners beginner

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:

  • -p wraps your code in a loop that reads each line into $_, applies the code, then prints $_.
  • -e allows 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. transliteration tr///: s/// is regex-based and more flexible, whereas tr/// is faster for simple character replacements.
  • -p vs -n: -p auto-prints $_, while -n only 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 g modifier 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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions