Alternative to Perl's <> in Raku?

Viewed 312

Here learning my way around Raku (neé Perl 6), very nice all around. But I sorely miss the magic <> from Perl 5, where you can just:

my $x = <>;
print $x;
while(<>) {
  print join(':', split);
}

(read next input line into $x, loop over the rest; input is from the files named as input or standard input if no file given). The "Perl 5 to 6" tutorials/migration guides/... just talk about slurping the whole file, or opening individual files by name. No magic "take input from named files in sequence" I can find.

I want the magic back!

2 Answers

The functionality you're looking for largely exists. This script:

my $x = get();
say "First: $x";
for lines() {
    .say
}

Given these inputs files:

$ cat foo
foo line 1
foo line 2
$ cat bar
bar line 1
bar line 2

Will, when invoked as:

raku script.p6 foo bar

Produce the output:

First: foo line 1
foo line 2
bar line 1
bar line 2

It will also take output from $*IN if there aren't files. The only thing that doesn't exist is a single replacement for <>, since that would depend on wantarray-like functionality, which is incompatible with multiple dispatch (and Raku considers multiple dispatch is far more useful).

The zero-arg candidates for get and lines are implemented in terms of $*ARGFILES, a file handle that provides the functionality of taking the files from the argument list or from $*IN - meaning one can pass it to any code that expects a file handle.

Enough magic for you?

sub MAIN( Str $file where *.IO.f  )
{
    .say for $file.IO.lines.map: *.comb.join(':');
}
Related