one-liners beginner

How to reverse lines in a file using perl -e?

Question

How to reverse lines in a file using perl -e?

To reverse lines of input using a Perl one-liner, it’s important to understand how Perl command-line flags work and how to structure your code so it runs correctly in the shell and sandbox.

Understanding the Perl one-liner flags

  • -n: wraps your code in a loop like while (<>) reading one line at a time but does not print automatically.
  • END { ... }: a special block that runs after all input has been read, perfect for outputting accumulated data.
  • The filename(s) must be provided as separate arguments outside the Perl code quotes, otherwise Perl parses incorrectly.

Why the original code fails in some sandboxes

  • Omitting spaces between code and filename causes Perl to treat the filename as part of the code, leading to syntax errors.
  • Using the wrong quoting or improper usage of flags results in bareword or operator errors.
  • To run with perl - (reading code from STDIN), you must write the Perl code as a script block rather than a one-liner with input filenames.

Correct, runnable example (no file access)

Here is a complete Perl script snippet you can run with perl - that reads lines from standard input, stores them, then prints them reversed on exit.

use strict;
use warnings;

my @lines;
while ( <> ) {
    push @lines, $_;
}
print reverse @lines;

You can execute this as:

echo -e "line one\nline two\nline three" | perl -

Paste the code above into the standard input, then press Ctrl-D (Unix) or Ctrl-Z (Windows) to end input and see the reversed lines:

line three
line two
line one

Notes on Perl syntax and context

  • $_ is the default variable that holds the current input line when reading <>.
  • @lines is an array collecting all lines. Using push appends to it.
  • reverse @lines returns the list in reversed order, which print outputs.
  • This script uses standard I/O and does not require any files or modules, safe for sandbox execution.

Summary

  • For one-liners reading from files, use: perl -ne 'push @lines, $_; END { print reverse @lines }' filename
  • When using perl - (code from STDIN) with no files, wrap your logic in a script reading from standard input by while(<>).
  • Always ensure filenames are outside Perl code quotes, and be mindful of shell quoting and syntax.

Following these guidelines will let you reverse lines safely and portably in Perl.

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