home | blog
Perl 6 screencast - part 4 - filesPublished on 2010.07.23 at 02:05:45Tags: Perl 6, Perl, screencast, files Direct link to the Perl 6 files screencast
See more Perl 6 entries.
Perl 6 Code examplesReading 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";
blog comments powered by Disqus
|