12

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!

TylerH
  • 20,799
  • 66
  • 75
  • 101
vonbrand
  • 11,412
  • 8
  • 32
  • 52

2 Answers2

19

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.

Jonathan Worthington
  • 29,104
  • 2
  • 97
  • 136
0

Enough magic for you?

sub MAIN( Str $file where *.IO.f  )
{
    .say for $file.IO.lines.map: *.comb.join(':');
}
Holli
  • 5,072
  • 10
  • 27
  • 3
    That's cool, and OP should try it, but it's not the same in a few ways. See jnthn's answer for how to emulate `<>`'s behavior, and note that raku's `.comb` without an argument splits a string into individual characters, whereas Perl's `split` without an argument is, afaik, `.split(/\s+/)` in raku. – raiph Mar 30 '20 at 21:20
  • 1
    An alternative to `.split` would be `.words` – https://docs.perl6.org/type/Str#routine_words – donaldh Mar 31 '20 at 17:07
  • 1
    Why, by the holy rngesus, do i keep forgetting about the `words` method? – Holli Mar 31 '20 at 21:58