How to get current line number during "raku -n" iteration?

Viewed 173

In Perl I could:

cat file.txt | perl -nE 'say $.' 

The closest Raku solution i found (without using state counter variable) returns position in bytes:

cat file.txt | raku -ne 'say $*IN.tell' 
2 Answers

Use a state variable for it and increment that. Most conveniently, there is the anonymous state variable $, meaning one can do:

echo -e "foo\nbar\nbaz" | perl6 -ne 'say $++ ~ ": $_"'

Which gives:

0: foo
1: bar
2: baz

Use ++$ instead for base-1 numbering. There isn't anything special built in to the handle; it falls neatly out of state variables or, for an explicit iteration, .lines.kv, and then it's only paid for by things that want it.

Related