HomePage RecentChanges Perl 6 Examples File

Perl 6 Example - Files

Open a file and read 1 line

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

Write to a file

#!Perl
#!/usr/local/bin/perl6

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

Read and word wrap the file

#!Perl
#!/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 '';
}

Software error:

Can't locate object method "endform" via package "CGI" at /data/scott.dd.com.au/wiki/modules/search.pl line 15.

For help, please send mail to the webmaster (webmaster@dd.com.au), giving this error message and the time and date of the error.