On Fri, 09 Jun 2017 03:42:36 -0700, tbrowder wrote:
> Add a line number method to IO::Handle so that it can be used on demand:
>
> my $fh = open "some-text", :linenumber, :index1;
>
> for $fh.lines -> $line {
> say "$fh.ln"; # output: 1
> last;
> }
Thank you for the suggestion, however, we're not going to add that feature in
core.
You can already get line numbering, by typing even fewer characters than what
your example demonstrates:
for 1..* Z "some-text".IO.lines -> ($ln, $line) {
say $ln; # output: 1
}
As you can see. It works without even involving the filehandle at all.
The problem with adding the method you suggest is it'll give wrong information
more often than not.
for $fh.lines »=>» 'a'..'z' {
say $fh.ln
}
Above, the method will always return the number of the last line, because the
hyper is evaluated eagerly.
for $fh.lines -> $line {
say $fh.ln;
say $fh.readchars: 2000;
}
Above, line numbering will get out of a whack, the second .readchars reads in
the $.nl-in chars. The solution to that would be to make all read
operations—even binary—scan their data for $.nl-in strings, which would make
our slow IO even slower. And it's even more problematic in binary read methods
since we might not be reading a chunk of valid $.encoding text.
for "file.txt".IO.lines -> $line {
say $fh.ln;
}
And the above won't work at all, since the file handle isn't available.
The aforementioned `1..* Z` method feels a fine solution to me, but if you
really want the `.ln`
method, create a module that mixes it in. IO::CatHandle::AutoLines does what
you want for cat
handles, so you should be able to re-use a lot of its guts.
[1] https://modules.perl6.org/dist/IO::CatHandle::AutoLines