Limiting a for loop in perl

Viewed 91

I have a bit of perl which is taking in data via a pipe and running

... | perl -0 -wnE 'say for /\d+/g'

which prints every numeric value passed from before the pipe. How would I change this syntax so that only the last ten found are printed?

2 Answers
... | perl -M5.010 -ne'say for /\d+/g' | tail -10
... | perl -nle'print for /\d+/g' | tail -10

Perl-only:

... | perl -M5.010 -ne'push @n, /\d+/g; splice(@n, 0, -10); END { say for @n }'
... | perl -nle'push @n, /\d+/g; splice(@n, 0, -10); END { print for @n }'

Notes:

  • -E isn't forward compatible, meaning that upgrading Perl could break the program. It should only be used in singe-use code. Replaced with -M5.010 -e.
  • -0 was an attempt to slurp the input file. That's not what it does. -0777 should be used for that. But there's no reason to slurp the input file here.

You can pipe it through the tail unix command to show only the last 10 numbers:

... | perl -0 -wnE 'say for /\d+/g' | tail -10
Related