Scott Penrose

Perl 6 Examples File

Scott is an expert software developer with over 30 years experience, specialising in education, automation and remote data.

Difference between revision 4 and current revision

No diff available.

Perl 6 Example - Files

Open a file and read 1 line

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


my $tempfile = open('output.txt', :w);
$tempfile.print("Hello world\n");
  • :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


my $line_length = 50;

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

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