Reading from a file in Perl 6

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.

Note! This site is about Perl 6.
If you are looking for a solution for Perl 5, please check out the Perl 5 tutorial.

Read line-by-line

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;

The Perl 6 Tricks and Treats newsletter has been around for a while. If you are interested to get special notification when there is new content on this site, it is the best way to keep track:
Full name:
This is a newsletter temporarily running on my personal site ( using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2013-03-19


In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus
Suggest a change
Elapsed time: 2.27525502

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.