home | blog

Perl 6 screencast - part 4 - files

Published on 2010.07.23 at 02:05:45 Bookmark and Share

Tags: Perl 6, Perl, screencast, files



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";



blog comments powered by Disqus
Follow szabgab on Twitter
Tags
Perl (270)
Perl 5 (94)
Padre (79)
Perl 6 (42)
IDE (41)
testing (38)
CPAN (28)
business (27)
newsletter (24)
marketing (23)
training (20)
TPF (17)
open source (17)
Windows (17)
promotion (17)
Parrot (16)
YAPC (16)
Israel (15)
grants (15)
Python (14)