Multiple signatures


That's ok but there are cases when the name of the template and the output file are different. So I need both versions. In Perl 6 it is not a problem, I can just define both of the functions, telling Perl that they are multies - so it won't think I am redefining a function by mistake.

examples/subroutines/multiple_signatures.p6
#!/usr/bin/perl6
use v6;

multi sub process_template($input, %params) {
	my $output = substr($input, 0, -4) ~ "html";
	say "open $input";
	say "replace {%params.perl}";
	say "save $output";
}

multi sub process_template($input, $output, %params) {
	say "open $input";
	say "replace {%params.perl}";
	say "save $output";
}

my %data = (
	fname => "Foo",
	lname => "Bar",
);

process_template("index.tmpl", %data);
process_template("from.tmpl", "to.html", %data);

The output will be:

examples/subroutines/multiple_signatures.p6.out
open index.tmpl
replace {"lname" => "Bar", "fname" => "Foo"}
save index.html
open from.tmpl
replace {"lname" => "Bar", "fname" => "Foo"}
save to.html

For every function call Rakudo will look for a function that matches the signature and call that function. If no match is found it will throw an exceptions so calling without a hash will throw a run-time exception: process_template("from.tmpl", "to.html"); Non-Associative argument for %params in call to process_template Sometimes that's what we want. In other cases we might want to allow the user to call the above functions without providing any parameters. We could write two additional functions without the %params but that just unnecessary code duplication. Instead we can declare the hash as optional:


Copyright 2006, 2007, 2008, 2009, 2010 Gabor Szabo http://szabgab.com/ Index | TOC
If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed