Skip to content

Instantly share code, notes, and snippets.

@masak
Created December 8, 2009 05:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masak/251434 to your computer and use it in GitHub Desktop.
Save masak/251434 to your computer and use it in GitHub Desktop.
On the ninth day of advent, we unwrap... the syntax for parameters and arguments.
You may or may not be familiar with the way Perl 5 does parameter handling in subroutines. It goes something like this:
<pre>
sub sum {
[+] @_
}
say sum 100, 20, 3; # 123
</pre>
The <code>[+]</code> is Perl 6, but we might as well have written that as <code>my $i = 0; $i += $_ for @_; $i</code>, and the above would have worked in Perl 5. The important point is that, in Perl 6 as well as in Perl 5, when you call a subroutine, your parameters can be found in <code>@_</code>. You unpack them, and you do your thing.
This system is extremely <em>flexible</em>, because it doesn't impose any mechanism on the handling of parameters; it's all up to you, the programmer. It's also <em>tedious</em>, and favours boilerplate to some extent. Take this fictional example:
<pre>
sub grade_essay {
my ($essay, $grade) = @_;
die 'The first argument must be of type Essay'
unless $essay ~~ Essay;
die 'The second argument must be an integer between 0 and 5'
unless $grade ~~ Int &amp;&amp; $grade ~~ 0..5;
%grades{$essay} = $grade;
}
</pre>
(You'd have to use <code>isa</code> instead of <code>~~</code> and <code>$grades</code> instead of <code>%grades</code> to make this work in Perl 5, but apart from that, this code would work in Perl 5 as well as in Perl 6.)
Now, for a moment, look at the above, and despair about the amount of manual unpacking and verification you have to make. Feel it? Good.
Perl 5 solves this by giving you excellent CPAN modules, such as <a href='http://search.cpan.org/~ovid/Sub-Signatures-0.21/lib/Sub/Signatures.pm'>Sub::Signatures</a> and <a href='http://search.cpan.org/~flora/MooseX-Declare-0.32/lib/MooseX/Declare.pm'>MooseX::Declare</a>, for example. Just include them, and you're set.
Perl 6 solves it by giving you a few more defaults. By "a few more", I really mean "make sure you don't drool on your keyboard". In Perl 6, I would have written the above routine like this:
<pre>
sub grade_essay(Essay $essay, Int $grade where 0..5) {
%grades{$essay} = $grade;
}
</pre>
<em>Now</em> we're talking. It has the same runtime semantics as the longer version above. And I didn't have to import any CPAN modules, either.
Sometimes it's convenient to provide default values to parameters:
<pre>
sub entreat($message = 'Pretty please, with sugar on top!', $times = 1) {
say $message for ^$times;
}
</pre>
The default values need not be constants, and they can in fact use earlier parameters:
<pre>
sub xml_tag ($tag, $endtag = matching_tag($tag) ) {...}
</pre>
If your default is <code>undef</code>, just mark the parameter as optional without giving it a default, by using <code>?</code>:
<pre>
sub deactivate(PowerPlant $plant, Str $comment?) {
$plant.initiate_shutdown_sequence();
say $comment if $comment;
}
</pre>
One feature I particularly like is that you can refer to the parameters by name when calling, passing the named arguments in any order you like. I can never remember the parameter order in functions like this:
<pre>
sub draw_line($x1, $y1, $x2, $y2) { ... }
draw_line($x1, $y1, $x2, $y2); # phew. got it right this time.
draw_line($x1, $x2, $y1, $y2); # dang! :-/
</pre>
There's a way to refer to the parameters by name, which makes this problem melt away:
<pre>
draw_line(:x1($x1), :y1($y1), :x2($x2), :y2($y2)); # works
draw_line(:x1($x1), :x2($x2), :y1($y1), :y2($y2)); # also works!
</pre>
The colon means "here comes a named argument", and the whole construct is to be read as <code>:name_of_parameter($variable_passed_in)</code>. There's a short form that can be used when the parameter and the variable happen to have the same name, though:
<pre>
draw_line(:$x1, :$y1, :$x2, :$y2); # works
draw_line(:$x1, :$x2, :$y1, :$y2); # also works!
</pre>
I like the short form. I find it causes my code to be more readable.
If you, as the API author, want to <em>force</em> people to use named arguments &mdash; which might actually be appropriate in the case of <code>draw_line</code> &mdash; you need only supply the colons in the subroutine signature.
<pre>
sub draw_line(:$x1, :$y1, :$x2, :$y2 ) { ... } # optional nameds
</pre>
But be careful, named arguments are optional by default! In other words, the above is equivalent to this:
<pre>
sub draw_line(:$x1?, :$y1?, :$x2?, :$y2?) { ... } # optional nameds
</pre>
If you want to explicitly make parameters required, you can append a <code>!</code> to them:
<pre>
sub draw_line(:$x1!, :$y1!, :$x2!, :$y2!) { ... } # required nameds
</pre>
Now the caller has to pass them, just as with ordinary positional parameters.
What about varargs? Say you want an arbitrary number of arguments passed in. No problem: just make the paramter an array and precede it with a <code>*</code>:
<pre>
sub sum(*@terms) {
[+] @terms
}
say sum 100, 20, 3; # 123
</pre>
I use the same example as we started out with to make a point: when you don't supply a signature to your subroutine, what you end up with is the signature <code>*@_</code>. This is the signature that emulates Perl 5 behaviour.
But an array with a <code>*</code> in front of it (a 'slurpy array') only captures positional arguments. If you want to capture named arguments, you'd use a 'slurpy hash':
<pre>
sub detect_nonfoos(:$foo!, *%nonfoos) {
say "Besides 'foo', you passed in ", %nonfoos.keys.fmt("'%s'", ', ');
}
detect_nonfoos(:foo(1), :bar(2), :baz(3));
# Besides 'foo', you passed in 'bar', 'baz'
</pre>
Oh, and this might be a good time to mention that you can also pass in named parameters with a more hash-like syntax, like so:
<pre>
detect_nonfoos(foo =&gt; 1, bar =&gt; 2, baz =&gt; 3);
# Besides 'foo', you passed in 'bar', 'baz'
</pre>
Here's one important difference to Perl 5: parameters are <code>readonly</code> by default:
<pre>
sub increase_by_one($n) {
++$n
}
my $value = 5;
increase_by_one($value); # boom
</pre>
There are two chief reasons for making parameters readonly; one being efficiency. Optimizers like when variables are read-only. The other reason has to do with encouraging the right habits in the programmer, and make it slightly more cumbersome to be sloppy. Functional programming is good not only for the optimizer, but for the soul as well.
Here's what you need to do to make the above work:
<pre>
sub increase_by_one($n is rw) {
++$n
}
my $value = 5;
say increase_by_one($value); # 6
</pre>
Sometimes <code>is rw</code> is what you want, but sometimes you'd rather be modifying a copy of whatever was sent in. That's when you use <code>is copy</code>:
<pre>
sub format_name($first, $middle is copy, $last) {
$middle .= substr(0, 1);
"$first $middle. $last"
}
</pre>
The original will be left unchanged.
In Perl 6, when you pass in an array or a hash, it doesn't flatten out over several arguments by default. Instead, you have to use the <code>|</code> to make it flatten.
<pre>
sub list_names($x, $y, $z) {
"$x, $y and $z"
}
my @ducklings = &lt;huey dewey louie&gt;;
try {
list_names(@ducklings);
}
say $!; # 'Not enough positional parameters passed;
# got 1 but expected 3'
say list_names(|@ducklings); # 'huey, dewey and louie'
</pre>
Similarly, if you flatten a hash, its contents will be sent in as named arguments to the routine.
Just as you can pass in arrays and hashes, you can also pass in code blocks:
<pre>
sub traverse_inorder(TreeNode $n, &amp;action) {
traverse_inorder($n.left) if $n.left;
action($n);
traverse_inorder($n.right) if $n.right;
}
</pre>
The three sigils are really type constraints:
<pre>
@ List
% Mapping
&amp; Code
</pre>
...with the <code>$</code> sigil working as the unconstrained version.
Watch out! An easy trap that people fall into is specifying the type constraint twice, both through a type and through a sigil:
<pre>
sub f(Array @a) { ... } # WRONG, unless you mean a List of Arrays
sub f( @a) { ... } # probably what you meant
sub f(Int @a) { ... } # Array of Int
</pre>
If you followed through to this point, you deserve another Perl 6 one-liner.
<pre>
$ perl6 -e '.fmt("%b").trans("01" =&gt; " #").say for &lt;734043054508967647390469416144647854399310&gt;.comb(/.**7/)'
### ## ###
# # ## # ## # #
### # # ## # ####
# #### # # # #
# # # # # #
# ## # ## ###
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment