For Perl one-liners with implicit loops (using -n
or -p
command line options), use last
or last LINE
to break out of the loop that iterates over input records. For example, these simple examples all print the first 2 lines of the input:
echo 1 2 3 4 | xargs -n1 | perl -ne 'last if $. == 3; print;'
echo 1 2 3 4 | xargs -n1 | perl -ne 'last LINE if $. == 3; print;'
echo 1 2 3 4 | xargs -n1 | perl -pe 'last if $. == 3;'
echo 1 2 3 4 | xargs -n1 | perl -pe 'last LINE if $. == 3;'
All print:
1
2
The perl one-liners use these command line flags:
-e
: tells Perl to look for code in-line, instead of in a file.
-n
: loop over the input one line at a time, assigning it to $_
by default.
-p
: same as -n
, also add print
after each loop iteration over the input.
SEE ALSO:
last
docs
last
, next
, redo
, continue
- an illustrated example
perlrun: command line switches docs
More examples of last
in Perl one-liners:
Break one liner command line script after first match
Print the first N lines of a huge file