Camelia
Prev: Passing arrays and hashes

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/env 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:


Prev: Passing arrays and hashes

Table of Contents

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.
Email:
Name: