How do I read from STDIN in Rakudo Perl6?
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.";
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.