11

As simple as that, how can I read input from STDIN in Perl6?

I reckon there's many ways of doing it, but I'm interested in the most idiomatic Perl6 solution.

Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
Cosimo
  • 2,846
  • 1
  • 24
  • 26

2 Answers2

12

The standard input file descriptor in Perl6 is $*IN (in Perl5 the *STDIN typeglob had a reference to the STDIN file descriptor as *STDIN{IO}).

One way of reading from standard input is the following:

for lines() {
    say "Read: ", $_
}

In fact, lines() without an invocant object defaults to $*IN.lines().

An alternative that uses a local variable is:

for $*IN.lines() -> $line {
    say "Read: ", $line
}

Would be cool to see more alternative ways of doing it.

Cosimo
  • 2,846
  • 1
  • 24
  • 26
  • 2
    Sure. `slurp()` without arguments slurps your `$*IN`. – Konrad Borowski Dec 15 '12 at 15:17
  • 3
    Tehcnically speaking, `*STDIN` is a typeglob not a file descriptor. The I/O handle(s) associated with that typeglob is `*STDIN{IO}`. The file descriptor number of the filehandle component of that I/O handle filehandle–dirhandle pair is `fileno(*STDIN{IO})`. – tchrist Dec 15 '12 at 16:54
  • @GlitchMr: why don't you make that an answer? – Christoph Dec 15 '12 at 21:27
  • @cosimo Add please also reading by blocks and/or different separator – analogy of [`$/`](http://perldoc.perl.org/perlvar.html#$INPUT_RECORD_SEPARATOR) variable. – Hans Ginzel Dec 17 '15 at 11:39
10

You can also slurp entire standard input using slurp without arguments. This code will slurp entire input and print it.

print slurp;

If you want to get lines, you can use lines() iterator, working like <> in Perl 5. Please note that unlike Perl 5, it automatically chomps the line.

for lines() {
    say $_;
}

When you want to get single line, instead of using lines() iterator, you can use get.

say get();

If you need to ask user about something, use prompt().

my $name = prompt "Who are you? ";
say "Hi, $name.";
Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71