How to print specific columns with perl -a?
Question
How to print specific columns with perl -a?
When using Perl from the command line, the -a flag enables autosplit mode which automatically splits each input line into the @F array using the input field separator specified by -F (default is whitespace). This allows easy extraction and printing of specific columns from input data.
How -a Works for Column Extraction
-aactivates autosplit on the input line, splitting it into the array@F.-nwraps your code in a loop iterating over each line of input.- Refer to columns using zero-based indexes like
$F[0]for the first column. -Flets you specify a custom input field separator if needed (e.g.,-F',').
Important Note on perl -a -n -e Usage
The common mistake is to run the command without proper quoting or mixing shell redirection and code. Also, -a only works combined with -n or -p. In some environments (like online sandboxes), command-line flags can get misinterpreted, so for a fully runnable example in one Perl script, it's better to emulate autosplit manually.
Runnable Perl Example Printing Specific Columns
This complete script uses Perl code only (no command-line flags) to demonstrate how -a works internally: it reads lines, splits into @F on whitespace, and prints columns 1 and 3 (zero-indexed $F[0] and $F[2]):
use strict;
use warnings;
while (my $line = ) {
chomp $line;
# simulate autosplit mode (-a) splitting on whitespace
my @F = split /\s+/, $line;
# print first and third columns
print "$F[0] $F[2]\n";
}
__DATA__
apple banana cherry date
foo bar baz qux
one two three four
This produces the output:
apple cherry
foo baz
one three
Summary and Gotchas
- In command-line usage,
-aseparates input lines into@Fautomatically. @Fis zero-based indexed;$F[0]is the first column.- Use
-Fto specify custom delimiters (e.g.,-F','for CSV). - Remember to quote your code correctly when using
perl -a -n -e 'code'to avoid shell issues. -nloops over input lines;-pdoes the same but prints each line automatically.- Testing with a full Perl script (like above) avoids command line parsing issues, especially in restricted environments.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 10ms
apple cherry
foo baz
one three
(empty)