Camelia
Prev: Twigils and special variables

Read line from file

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

As in other high level languages one has to open a file in order to read from it or to write to it. In Perl 6 it is done by the open() function imported from the IO class. It can receive several parameter but these two are very important: The name of the file and the mode. In order to open a file for reading the mode need to be :r. The function either returns a file handle that should be placed in a scalar variable or throws an exception in case of failure.

$fh = open $filename, :r

Once we have an open file handler we can use the get method ($fh.get) to read one line from the given file.

One could read many lines using consecutive calls to the get method but there are better ways to do that.

The specifications of all the IO of Perl 6 can be found in S32-setting-library/IO.pod

tutorial/files/read_one_line.p6

#!/usr/bin/env perl6
use v6;

my $filename = $*PROGRAM-NAME;

my $fh = open $filename;
my $line = $fh.get;
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:
Email:
Full name:
This is a newsletter temporarily running on my personal site (szabgab.com) using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2012-01-01


Prev: Twigils and special variables

Comments

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.4766109

Support my Perl 6 book!

I am writing a book on Web Application Development in Perl 6 and raising money via crowdfunding. Please support my effort!

Perl 6 Tricks and Treats newsletter

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