Perl One-Liners & Practical Text Processing

Perl Intermediate/Advanced — Perl One-Liners & Practical Text Processing
Perl Intermediate/Advanced
Course 2 · Chapter 9 · Perl One-Liners & Practical Text Processing

⚡ Perl One-Liners & Practical Text Processing

The final chapter — and where this whole course's opening framing pays off directly. Course 1, Chapter 1 introduced Perl as "what you reach for once shell text-processing hits its ceiling," positioned against the site's own Bash/SED/AWK/regex1 cluster. This chapter shows Perl competing on sed's and awk's own turf: the command-line one-liner.

▶️ perl -e — Running Code Without a Script File

perl -e 'print "Hello\n";' perl -e 'print 2**10, "\n";' # 1024 — a quick calculation, no .pl file needed at all

-e runs the given code directly, no script file required — genuinely useful for a quick calculation or test without leaving the terminal.

🔁 perl -n — Implicit Loop Over Input Lines

perl -ne 'print if /error/;' access.log # equivalent to: grep 'error' access.log

-n wraps your code in an implicit while (<>) { ... } loop — one iteration per input line, without writing that loop yourself. <> is the "diamond operator" — the generic version of Course 1, Chapter 8's <$fh>, reading from whatever files are named on the command line, or standard input if none are given. Inside the loop, each line is available as $_, the same default variable from Chapter 6's bare regex matches and Chapter 7's map/grep.

🖨️ perl -p — Implicit Loop with Automatic Printing

perl -pe 's/foo/bar/;' file.txt # equivalent to: sed 's/foo/bar/' file.txt

-p behaves like -n, but automatically prints $_ at the end of every iteration — the go-to flag for line-by-line transformation, directly replicating what sed 's/pattern/replacement/' does, using Chapter 1's own s///.

💾 perl -i — In-Place Editing

perl -i.bak -pe 's/foo/bar/;' file.txt # modifies file.txt directly, keeping file.txt.bak as a backup
⚠ -i With No Backup Suffix Is Irreversible

perl -i -pe '...' file.txt (no suffix after -i) overwrites the file directly, with no undo — a typo'd pattern can silently and permanently destroy real data. Always test the exact same command without -i first (it prints the transformed output to the terminal without touching the file), or run with -i.bak to keep an automatic backup, before ever running it for real against something you can't afford to lose.

🚩 Useful Command-Line Flags Combined

FlagEffect
-eRun code given directly on the command line
-nImplicit line-reading loop, no automatic printing
-pImplicit line-reading loop, WITH automatic printing
-i[.suffix]Edit files in place, optionally keeping a backup
-lAutomatically handles line endings (chomps input, adds newline to output)
-aAutosplits each line into @F by whitespace — genuinely awk-like field splitting
-FSets a custom field separator for -a (e.g. -F, for CSV)
perl -F, -lane 'print $F[1];' data.csv # -a splits each line into @F by the -F, delimiter — prints the 2nd column of a CSV

⚔️ A Direct Comparison — Perl vs. sed vs. awk

TasksedawkPerl
Replace textsed 's/foo/bar/' fawk '{gsub(/foo/,"bar")}1' fperl -pe 's/foo/bar/' f
Print matching linessed -n '/err/p' fawk '/err/' fperl -ne 'print if /err/' f
Print 2nd column(awkward in sed)awk -F, '{print $2}' fperl -F, -lane 'print $F[1]' f

Perl's one-liner syntax is more verbose than sed's for the simplest substitutions, but scales considerably better the moment a task needs anything sed/awk don't handle natively — real subroutines, complex data structures, or CPAN modules (Chapter 5) — without switching tools entirely.

🔧 A Worked Example — Practical One-Liners

# count lines matching a pattern: perl -ne '$c++ if /ERROR/; END { print "$c\n" }' app.log # extract email addresses from a file: perl -ne 'print "$1\n" while /([\w.+-]+@[\w-]+\.[\w.-]+)/g;' contacts.txt # number every line: perl -ne 'print "$.: $_";' file.txt # $. is the current input line number # sum a column of numbers: perl -lne '$sum += $_; END { print $sum }' numbers.txt

Every one of these reuses tools from earlier in this course directly — Chapter 6's regex captures, Chapter 4's/Chapter 2's context-driven accumulation, and the special END { } block (runs once, after all input has been processed) for a final summary.

One-Liner vs. Full Script vs. sed/awk — When to Reach for Which

A one-liner is right for a genuinely quick, one-off task at the terminal — something you'd otherwise open an editor for and immediately throw away. The moment a task needs to be run more than once, tested (Chapter 8), or exceeds a few lines of real logic, a proper script (everything else in this course) is the better tool — readable, maintainable, version-controllable. sed and awk remain excellent for the simplest cases they were purpose-built for; Perl one-liners are worth reaching for the moment a task needs slightly more power than either comfortably provides, without needing to abandon the one-liner workflow entirely.

-e

Run code directly, no script file.

-n / -p

Implicit line loop, with or without automatic printing.

-i[.bak]

Edit files in place — always use a backup suffix until confident.

-a / -F

Autosplit fields — Perl's genuinely awk-like column-processing mode.

💻 Coding Challenges

Challenge 1: Replace Text with -pe

Write a perl -pe one-liner that replaces every occurrence of "cat" with "dog" (case-insensitive) in a file, first WITHOUT -i to preview the change, then WITH -i.bak to apply it safely.

→ Solution

Challenge 2: Count and Print with -ne

Write a perl -ne one-liner that counts how many lines in a file contain the word "WARN", printing just the final count using an END block.

→ Solution

Challenge 3: Extract a CSV Column

Given a CSV file with columns name,age,city, write a perl -F -lane one-liner that prints just the city column (the 3rd field) for every row.

→ Solution

🎓 Course Complete!

That's all 9 chapters of Perl Intermediate/Advanced — advanced regex, context internals, classic and modern OOP, modules and CPAN, error handling, closures, testing, and one-liners — and with it, the complete Perl track: Fundamentals and Intermediate/Advanced, 18 chapters combining a genuinely practical, work-relevant language with the site's own broader Bash/SED/AWK/regex1 text-processing cluster it was framed against from the very first chapter.