one-liners intermediate

How to sum numbers in a file using perl one-liner?

Question

How to sum numbers in a file using perl one-liner?

Summing numbers in a file is a frequent task in Perl, often done using compact one-liners designed for quick command-line use. Perl’s strengths lie in its text-processing capabilities and flexible syntax, allowing you to easily extract and sum numbers in different contexts.

Common Pitfall: Running Perl One-Liners in a Restricted Environment

In sandboxed environments (like perl - with direct code input), command-line flags (-n, -E, -e) are not accepted the same way as when running from a shell prompt. This causes syntax errors like:


String found where operator expected at - line 1, near "nE '$sum += $_; END { say $sum }'"

Because the one-liner is interpreted literally as Perl code, you must rewrite it as a full script that runs inside the sandbox.

How to Sum Numbers Within the Script Passed to perl -

Instead of relying on one-liner switches, write plain Perl code:

  • Read input lines from STDIN (the default input handle <>).
  • Extract numbers using regex and sum them.
  • Print the final sum at the end.

Example: Summing All Numbers from Standard Input


use strict;
use warnings;

my $sum = 0;

while (<>) {
    while (/(\d+)/g) {
        $sum += $1;
    }
}

print "$sum\n";
__DATA__
12
7 apples and 5 oranges
10

This script reads lines from standard input (or __DATA__ in this example), matches all occurrences of digits, accumulates their sum, and prints it.

How to Run This Code

Save the above into a file sum_numbers.pl and run:


perl sum_numbers.pl input.txt

Or simulate input by typing:


echo -e "12\n7 apples and 5 oranges\n10" | perl sum_numbers.pl

Because environment restrictions prevent command-line switches, this approach works reliably in sandboxed interpreters.

Summary of Key Points

  • Command-line switches like -n or -E cannot be passed inside perl - mode; use full Perl scripts instead.
  • while (<>) reads from standard input or files specified on command line.
  • Use regex /(\d+)/g to extract all numbers in each line, not just one per line.
  • Summation variable $sum uses scalar sigil $ and accumulates all numbers found.
  • Print the final result after input processing ends.

This approach ensures robust, easily understandable Perl code that works in any environment, including restricted sandboxes.

Verified Code

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

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

Was this helpful?

Related Questions