Chapter 3. Numbering

In this chapter, we’ll look at various one-liners for numbering lines and words, and you’ll get to know the $. special variable. You’ll also learn about Perl golfing, a “sport” that involves writing the shortest Perl program to get a task done.

3.1 Number all lines in a file

perl -pe '$_ = "$. $_"'

As I explained in one-liner 2.1 (page 7), -p tells Perl to assume a loop around the program (specified by -e) that reads each line of input into the $_ variable, executes the program, and then prints the contents of the $_ variable.

This one-liner simply modifies $_ by prepending the $. variable to it. The special variable $. contains the current line number of the input. The result is that each line has its line number prepended.

Get Perl One-Liners now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.