Camelia
Prev: Passing arrays and hashes

Multiple signatures

Note! This site is about Perl 6.
If you are looking for a solution for the current production version of Perl 5, please check out the Perl 5 tutorial.

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.

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

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


The Perl 6 Tricks and Treats newsletter has been around for a while. If you are interested to get special notification when there is new content on this site, it is the best way to keep track:
Email:
Full name:
This is a newsletter temporarily running on my personal site (szabgab.com) using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2012-01-01


Prev: Passing arrays and hashes

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus
Suggest a change
Elapsed time: 3.4766929

Perl 6 Tricks and Treats newsletter

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