← Back to Perl Course | Chapter 1: Introduction | Lesson 7 of 7

Perl one-liners

The -e switch lets you run a tiny Perl program straight from the command line.

In this page:

  1. Perl one-liners

Perl one-liners

perl -e followed by quoted code runs it without a file. Useful switches include -n (loop over each input line), -p (loop and print each line), -l (handle newlines for you) and -i (edit files in place). One-liners are popular for quick text transformations in shell pipelines.

Note: Use -w or put use warnings inside the code to see warnings in one-liners.

Example: Perl one-liners

bash
$ perl -e 'print "Hello from a one-liner\n"'
Hello from a one-liner

$ echo "perl is fun" | perl -pe 's/perl/Perl/'
Perl is fun

$ perl -lne 'print length' words.txt
$ perl -i.bak -pe 's/cat/dog/g' notes.txt

⚠️ Run this in your own terminal or Node.js environment.

Common Mistakes
  1. Forgetting the quotes around the code so the shell splits it
  2. Mixing up -n (no automatic print) and -p (prints each line)
  3. Using -i without a backup suffix on files you cannot recover
Chapter Summary
  • perl -e runs code from the command line
  • -n loops over input lines
  • -p loops and prints each line
  • -i edits files in place
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.