one-liners beginner

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

  • -a activates autosplit on the input line, splitting it into the array @F.
  • -n wraps 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.
  • -F lets 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, -a separates input lines into @F automatically.
  • @F is zero-based indexed; $F[0] is the first column.
  • Use -F to 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.
  • -n loops over input lines; -p does 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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
apple cherry
foo baz
one three
STDERR
(empty)

Was this helpful?

Related Questions