shell-mastery — Perl

Perl One-Liners (competition essentials)

Print specific field (like awk '{print $2}')
perl -ane 'print "$F[1]\n"' file.txt
# -a: autosplit into @F, -n: loop over lines, -e: execute
Search and replace (like sed 's/old/new/g')
perl -pe 's/old/new/g' file.txt
perl -i -pe 's/old/new/g' file.txt   # in-place edit
Print lines matching pattern (like grep)
perl -ne 'print if /pattern/' file.txt
perl -ne 'print if /error/i' file.txt   # case-insensitive
Print line numbers (like grep -n)
perl -ne 'print "$.: $_" if /pattern/' file.txt
Extract regex matches (like grep -oP)
perl -ne 'print "$1\n" while /(\d+\.\d+\.\d+\.\d+)/g' file.txt
Sum a column (like awk '{sum+=$1} END{print sum}')
perl -ane '$s+=$F[0]; END{print "$s\n"}' file.txt
Unique lines preserving order (like awk '!seen[$0]++')
perl -ne 'print unless $seen{$_}++' file.txt
CSV processing
perl -F, -ane 'print "$F[0] $F[2]\n"' data.csv
Multi-line search
perl -0777 -ne 'print "$1\n" while /BEGIN(.*?)END/gs' file.txt
JSON extraction (no jq needed)
perl -MJSON -ne '$d=decode_json($_); print $d->{name}' data.json
Network: extract IPs and count
perl -ne 'print "$1\n" while /(\d+\.\d+\.\d+\.\d+)/g' access.log | sort | uniq -c | sort -rn | head -10
Replace across multiple files
perl -i -pe 's/10\.50\.1\.20/10.50.1.21/g' *.conf

Perl vs awk vs sed — When to Use What

Task sed awk perl

Simple substitution

sed 's/a/b/g'

overkill

perl -pe 's/a/b/g'

Field extraction

painful

awk '{print $2}'

perl -ane 'print "$F[1]\n"'

Complex regex

limited

limited

perl -ne '/(?<ip>\d+\.\d+)/; print $+{ip}'

In-place edit

sed -i

gawk -i inplace

perl -i -pe

Multi-line

hold buffer (hard)

RS tricks

perl -0777 (easy)

Binary data

no

no

yes (binmode)

JSON/XML

no

no

yes (modules)

Rule of thumb: sed for substitutions, awk for columns, perl for everything else.