TExcelTAD
Home › Perl › Perl One-liners

Perl One-liners

Perl is famous for one-liners: tiny programs typed directly at the shell prompt with perl -e. A handful of command-line switches wrap your code in a loop over the input lines, which turns Perl into a supercharged grep, sed and awk in one tool.

The commands in this lesson run in a terminal, not in the browser, so each one is paired with a runnable script that does exactly what the switches generate.

The key switches

Switch Effect
-e 'CODE' run CODE (may be given several times)
-n wrap the code in while (<>) { ... }: loop over input lines, print nothing automatically
-p like -n, but print $_ after each iteration (like sed)
-l chomp each input line, and add \n to every print
-a autosplit: with -n/-p, split each line into @F on whitespace
-F: the pattern for -a to split on (here a colon)
-i / -i.bak edit files in place (optionally keeping a backup)
-M Module use Module; before running

<> (the "diamond" operator) reads lines from the files named on the command line, or from standard input when there are none.

-n: grep-like filtering

bash
# Print lines containing ERROR (like grep)
perl -ne 'print if /ERROR/' app.log

# Print line numbers with each match
perl -ne 'print "$.: $_" if /timeout/i' app.log

-n turns the code into this program, here reading from DATA instead of the files:

perl · try it yourself
use strict;
use warnings;

while (<DATA>) {
    print "$.: $_" if /timeout/i;
}

__DATA__
INFO start
WARN Timeout on db
INFO retry
ERROR timeout again
2: WARN Timeout on db
4: ERROR timeout again

-p: sed-like editing

bash
# Replace every "colour" with "color" and print all lines
perl -pe 's/colour/color/g' essay.txt

# The same, editing the file in place and keeping essay.txt.bak
perl -i.bak -pe 's/colour/color/g' essay.txt

-p adds an automatic print at the end of each iteration (inside a continue block):

perl · try it yourself
use strict;
use warnings;

while (<DATA>) {
    s/colour/color/g;
} continue {
    print;
}

__DATA__
My favourite colour is blue.
Colours: red, colour of fire.
My favourite color is blue.
Colours: red, color of fire.

Only lowercase colour is replaced; add /i to the substitution to catch Colours too.

-a and -F: awk-like columns

bash
# Print the first and third whitespace-separated columns
perl -lane 'print "$F[0] $F[2]"' data.txt

# Sum the 3rd field (user ids) of /etc/passwd-style lines (colon-separated)
perl -F: -lane '$sum += $F[2]; END { print $sum }' /etc/passwd

With -a, each line is split into the array @F. END { ... } runs once after all input has been read, which is the place for totals:

perl · try it yourself
use strict;
use warnings;

my $sum = 0;
while (<DATA>) {
    chomp;                          # from -l
    my @F = split /:/;              # from -a with -F:
    $sum += $F[2];
    print "$F[0] has id $F[2]\n";   # -l would add the newline
}
print "Sum of ids: $sum\n";         # the END block

__DATA__
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
maya:x:1000:1000:Maya:/home/maya:/bin/bash
root has id 0
daemon has id 1
maya has id 1000
Sum of ids: 1001

A one-liner cookbook

Task One-liner
Count lines perl -lne 'END { print $. }' file
Print lines 10 to 20 perl -ne 'print if 10 .. 20' file
Remove trailing whitespace in place perl -i -pe 's/\s+$/\n/' file
Print unique lines, keeping order perl -ne 'print unless $seen{$_}++' file
Number all lines perl -pe '$_ = "$.\t$_"' file
Reverse the lines of a file perl -e 'print reverse <>' file
Word frequency perl -lne '$c{lc $_}++ for /\w+/g; END { print "$c{$_} $_" for sort { $c{$b} <=> $c{$a} } keys %c }' file
Sum a column perl -lane '$t += $F[1]; END { print $t }' file
Convert CRLF to LF perl -pi -e 's/\r$//' file

Note that one-liners usually skip use strict: they are throwaway code, and strict would demand my for %seen and friends.

Here is the "unique lines" and "word frequency" logic as a full program:

perl · try it yourself
use strict;
use warnings;

my (%seen, %count);
while (my $line = <DATA>) {
    chomp $line;                     # the last line may lack a newline
    print "unique: $line\n" unless $seen{$line}++;
    $count{lc $_}++ for $line =~ /\w+/g;
}
for my $w (sort { $count{$b} <=> $count{$a} || $a cmp $b } keys %count) {
    print "$count{$w} $w\n";
}

__DATA__
the cat sat
The dog sat
the cat sat
unique: the cat sat
unique: The dog sat
3 sat
3 the
2 cat
1 dog

Tip: On Windows cmd.exe, wrap one-liners in double quotes instead of single quotes, and use qq{} inside the code for strings.

Test yourself

Which switch prints every line automatically after your code runs?

  1. -n
  2. -p
  3. -a
  4. -l

With -a, where are the fields of each line stored?

  1. @ARGV
  2. @_
  3. @F
  4. %F

What does perl -i.bak -pe 's/a/b/' notes.txt do?

  1. Prints notes.txt
  2. Edits notes.txt in place and keeps the original as notes.txt.bak
  3. Creates notes.bak only
  4. Deletes notes.txt