It can be interesting to do operations on existing data structures in Perl 6, but without Input and Output, that would have limited usability in the real world.
Therefore reading from files is a critical operation.
The open function will open a file, by default for reading thought you could explicitly tell it by passing :r as a second parameter. Open will return the filehandle, an instance of the IO class.
The get method will read and return one line from the file. The trailing newline will be automatically removed. (Perl 5 developers will think that get automatically calls chomp as well.)
my $fh = open $filename; my $line = $fh.get;
You can also read all the lines of a file in a while loop. As opposed to Perl 5, there is not implicit check for defined-ness in such a while loop. You have to explicitly add the word defined in the condition. Otherwise the reading will stop on the first empty line.
my $fh = open $filename;
while (defined my $line = $fh.get) {
say $line;
}
A style that is probably much more Perl 6-ish would be to use the lines method in a for loop. The lines method will lazily (!) read all the lines of the file, assign it to the $line variable and execute the block.
my $fh = open $filename;
for $fh.lines -> $line {
say $line;
}

Published on 2013-03-19