one-liners beginner

How to trim whitespace from lines using perl -pe?

Question

How to trim whitespace from lines using perl -pe?

How to Trim Whitespace from Lines Using perl -pe

Using perl -pe on the command line is a very concise and effective way to trim leading and trailing whitespace from each line of input. The -p flag wraps your code in an implicit loop that reads each line into $_, executes your code, then prints $_. The -e flag lets you specify the code inline.

The standard regex substitution to trim whitespace is:

s/^\s+|\s+$//g;

This removes any whitespace at the start (^\s+) or end (\s+$) of the line.

Why perl -pe 's/^\s+|\s+$//g' Works on the Command Line but Not with perl -

The flags -p and -e are command-line options parsed by the Perl interpreter, not Perl code themselves. If you try to run this as input to perl - (reading code from STDIN), Perl sees the string perl -pe 's/^\s+|\s+$//g' as code, which causes a syntax error.

To implement the same trimming logic in a Perl script that you run using perl - (without flags), you must write the loop explicitly:

Runnable Perl Example: Trimming Whitespace from Lines (Executable with perl -)

use strict;
use warnings;

while (<>) {
    s/^\s+|\s+$//g;   # Trim leading and trailing whitespace from $_
    print "$_\n";     # Print the trimmed line with newline
}

# Example usage:
# echo "  hello  " | perl -  (then paste the above code)

Explanation of Perl Concepts

  • Implicit variable $_: The default variable where input lines are stored in while(<>){} loops and where s/// operates if no target is given.
  • Regex substitution operator s///: Modifies $_ by removing whitespace at the start/end of the line.
  • Context: In perl -pe, the loop and print are automatic. Without those flags, you must write them explicitly.
  • TMTOWTDI (There’s More Than One Way To Do It): You can also split this into two substitutions: s/^\s+//; s/\s+$//;

Common Pitfalls

  • Confusing command-line flags -pe with Perl code: You cannot input flags as code lines to perl -.
  • Omitting the explicit print statement if not using -p.
  • Forcing the global modifier g is unnecessary here. Since the patterns anchor to line start/end, it’s safe but slightly redundant.

Summary

Use perl -pe 's/^\s+|\s+$//g' on the command line for simple trimming. When running Perl code via perl - (reading code from STDIN), you must write the loop explicitly as shown in the example above for it to run successfully.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 11ms

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

Was this helpful?

Related Questions