one-liners intermediate

How to print every Nth line with perl one-liner?

Question

How to print every Nth line with perl one-liner?

How to Print Every Nth Line Using a Perl Script

To print every Nth line from input in Perl, you often see one-liners using -n or -p flags along with the special variable $. which tracks the current input line number.

However, in sandboxed or restricted environments where command-line switches such as -n or -p don’t work or you want a pure script to run with perl -, you can write a simple loop to read lines from <> (standard input), track the line number manually, and print every Nth line.

Key Perl Concepts

  • $. : A magic variable that stores the current line number when reading from files or input, but it may not behave as expected in all environments.
  • <>: The diamond operator reads lines from standard input or files listed on the command line.
  • Using a manual line counter guarantees consistent behavior, especially when $. resets or behaves unpredictably.

Runnable Perl Code to Print Every 3rd Line (via perl -)

This script reads lines from standard input and prints every 3rd line, using a manual counter for maximum compatibility:

use strict;
use warnings;

my $N = 3;
my $line_num = 0;

while (<>) {
    $line_num++;
    print if $line_num % $N == 0;
}

How to run: Save the above code into a file or run via standard input using:

perl -

Then type or paste lines and press Ctrl+D (or Ctrl+Z on Windows) to end input. The script will print every 3rd line it receives.

Common Gotchas

  • Using $. can sometimes be unreliable or reset unexpectedly, especially with switches or multiple input files.
  • Manual counters like $line_num ensure predictable counting behavior.
  • Off-by-one errors: Make sure to increment the counter before testing the modulo operation.
  • Context: print inside a loop prints in scalar context, and using while (<>) reads line by line in list context.

Summary

While Perl one-liners with -n or -p are concise for printing every Nth line, using a minimal script with a manual line counter ensures reliable execution in restricted environments or sandboxes without command-line flag support.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 8ms

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

Was this helpful?

Related Questions