Perl 6 Example - Files

Open a file and read 1 line

#!/usr/local/bin/perl6
my $tempfile = open('lorem.txt', :r);
my $first_line = $tempfile.get;
say $first_line;

  • "my" at the start of variables for lexical scoping
  • "open" to open a filename. 'lorem.txt' for a filename, :r to say read
  • File handle is an object, you can call ".get" to get a line
  • "say" is convenient method to print to STDOUT, and automatically adds a new line.

Write to a file

#!/usr/local/bin/perl6

my $tempfile = open('output.txt', :w);
$tempfile.print("Hello world\n");
$tempfile.close;

  • :w to open a file for write
  • File handle is an object, you can call print
  • Close as method on object.

Read and word wrap the file

#!/usr/local/bin/perl6

my $line_length = 50;

my $tempfile = open('lorem.txt', :r);
my $count = 0;
for $tempfile.lines {
	$count++;
	lines(words($_));
}

exit 0;

# Split a line into words (array)
sub words ($in) {
	return $in.split(/\s/);
}

# Print words, new line at word wrap, new line for paragraph
sub lines (@in) {
	my $length = 0;
	for @in -> $l {
		if ( ($length + $l.chars) < $line_length) {
			print $l ~ ' ';
			$length += $l.chars;
		}
		else {
			say '';
			$length = 0;
		}
	}
	say '';
}

  • Loops, Subs, Integer increments - all as you would expect
  • Subs allow variables in declaration (arguments)
  • Array (@) is always an array, even if passed in as a single argument. You don't need to take a reference like perl5
  • Concatenation of strings is done with "~"