Perl 6 screencast - part 4 - files

This article is about Perl 6. If you are looking for solution regarding the current production version of Perl 5, please check out the Perl tutorial.


Direct link to the Perl 6 files screencast

See more Perl 6 entries.

Perl 6 Code examples

Reading in all the lines of a file in a single scalar using the slurp function:

use v6;

my $content = slurp "text.txt"; say $content.chars;

Reading in all the lines of a file into the first element of an array using the slurp:

use v6;

my @content = slurp "text.txt"; say @content.elems; say @content[0].chars;

Reading in all the lines, each line in a separate element of the array using the lines function:

use v6;

my @content = lines "text.txt"; say @content.elems; say @content[0].chars;

Iterating over the lines one by one. lines is evaluated lazily here:

use v6;

for lines "text.txt" -> $line { say $line.chars; }

Opening a file using the open function. Reading in one line using the get method. Iterating over the rest of the file using the lines method:

use v6; my $fh = open "text.txt";

my $first_line = $fh.get; say $first_line;

for $fh.lines -> $line { say $line.chars; }

Opening a file for writing, printing a string to it using the say method and then closeing it to flush all the buffered output. Then re-reading the file just to show what happened.

use v6;

my $fh = open "out.txt", :w; $fh.say("text 4"); $fh.close;

say slurp "out.txt";