Here is a small collection of Perl 6 code snippets lifted and mangled from pugs/examples/cookbook
# ARRAYS
my @a = <94 13 97 95>;
for @a -> $e {
say $e;
}
# HASHES
my %hash = (
'one' => 'un',
'two' => 'deux',
'three' => 'trois'
);
for %hash.keys -> $key {
say "$key => %hash{$key}";
}
for %hash.kv -> $key, $value {
say "The word '$key' is '$value' in French.";
}
# SUBROUTINES
sub perl5 {
my ($x) = @_;
say $x;
}
perl5('old-fashioned');
sub parameters ($foo) { say $foo }
parameters('some parameter');
parameters 'some parameter';
parameters foo => 'some parameter';
parameters :foo('some parameter');
sub whole (@names, %flags) {
for @names -> $name {
say $name;
}
for (%flags.kv) -> $key, $value {
say "$key => $value";
}
}
my @stuff = ('array', 'elements');
my %flags = (hash => 'elements', are => 'pairs');
whole(@stuff, %flags);
sub optional ($required, $optional?) {
my $second_arg = $optional // 'Told you it was optional!';
say $required;
say $second_arg;
}
optional('this');
optional('this', 'that');
sub named_params ($first, :$second, :$third) {
say $first, $second, $third;
}
named_params(1, second => 2, third => 3);
sub transport ($planet, *@names) {
say "Transporting to $planet:";
for @names -> $name {
say "\t$name";
}
}
transport('Magrathea', 'Arthur', 'Ford', 'Ovid');
sub typed (Int $val) {
say $val + 3;
}
typed(3);
# LOOP OVER STDIN
while $_ = =<> {
.print;
}
# OPEN A FILE FOR READING
my $input = open("myfile.txt", :r) err die $!;
my $line = $input.readline;
$input.close;
# OPEN A FILE FOR WRITING
my $output = open("out.txt", :w) err die $!;
$output.say("blah");
$output.close;
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.