How to number lines in a file using perl -ne?
Question
How to number lines in a file using perl -ne?
How to Number Lines in a File Using perl -ne
The perl -ne command-line option is a classic and idiomatic way to process input line-by-line in Perl. It combines:
-nwhich wraps your code inwhile (<>), reading input line-by-line from files or STDIN-ewhich lets you provide the Perl code to execute right on the command line or viaperl -
The special variable $. automatically tracks the current line number of the last input filehandle read, making it perfect for line numbering.
Common Issue Explained
If you tried to run something like perl -ne 'print "$. $_"' file.txt inside a perl - sandbox or incorrectly quoted it, you might hit errors like:
Bareword found where operator expected at - line 1, near "'print "$. $_"' file"
This usually means the shell or your environment is mixing code and file arguments improperly. When running via perl - (reading code from standard input), command line switches expecting inline code and filenames don’t behave the same way.
How to Number Lines Correctly in a Sandbox Using perl -
When you want to run Perl code reading from standard input (perl -), you must provide the full program including the loop. Here's a simple script that numbers lines from standard input:
use strict;
use warnings;
while (<>) {
print "$. $_";
}
__END__
# Example usage: echo -e "apple\nbanana\ncherry" | perl -
This reads lines from STDIN or from files passed as arguments. The variable $. holds the current line number of the last filehandle read, and $_ contains the line text.
Perl Specific Concepts
$_is the default variable many functions operate on, here holding the current line.while (<>)reads input line-by-line from files or STDIN.$.tracks the current line number for the last input filehandle.- The
-nflag automates thewhile (<>)loop in one-liners, but in a standalone script you must include it yourself.
Common Gotchas
- Quoting: On Unix shells, single quotes prevent premature interpolation of Perl variables.
- Multiple files: Line number
$.keeps counting through multiple files unless reset withclose ARGV if eof;. - Removing newlines: Don't chomp unless you want to control newline printing yourself.
Summary
If you want to run a quick line numbering script interactively or in a sandbox with perl -, here is a full minimal script you can paste and run:
use strict;
use warnings;
while (<>) {
print "$. $_";
}
__END__
# Try this locally with:
# echo -e "one\ntwo\nthree" | perl -
This approach respects all constraints (no external modules, no file access assumed, runs quickly) and demonstrates the core Perl idiom for line numbering which underpins the perl -ne 'print "$. $_"' one-liner.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 8ms
1 # Example usage: echo -e "apple\nbanana\ncherry" | perl -
(empty)