Skip to content

Instantly share code, notes, and snippets.

@manwar
Last active February 27, 2025 17:32
Multi-methods in Perl and Raku.

In Perl, you can't have two subroutines with the same name even if you have different set of parameters but in Raku you can with the help of keyword multi.

However, thanks to the CPAN module Class::Multimethods by Damian Conway, we can get the similar functionality.

Here is a very simple example:

#!/usr/bin/env perl

use v5.38;
use Class::Multimethods;

multimethod greet => ('$') => sub {
    return "Hello $_[0].";
};

multimethod greet => ('$', '$') => sub {
    return "Hello $_[0] and $_[1].";
};

say greet('Joe');            # Hello Joe.
say greet('Joe', 'Billy');   # Hello Joe and Billy.

Or using CPAN module Multi::Dispatch by Damian Conway as suggested by Dave Cross.

#!/usr/bin/env perl

use v5.38;
use Multi::Dispatch;

multi greet($name) {
    return "Hello $name.";
}

multi greet($name1, $name2) {
    return "Hello $name1 and $name2.";
}

say greet('Joe');            # Hello Joe.
say greet('Joe', 'Billy');   # Hello Joe and Billy.

Let's check the result:

  $ perl multi.pl
  Hello Joe.
  Hello Joe and Billy.
  $

Let's do the same in Raku.

#!/usr/bin/env raku

use v6;

multi greet(Str $name) returns Str {
    return "Hello $name.";
}

multi greet(Str $name1, Str $name2) returns Str {
    return "Hello $name1 and $name2.";
}

say greet('Joe');            # Hello Joe.
say greet('Joe', 'Billy');   # Hello Joe and Billy.

Time to test the code:

  $ raku multi.raku
  Hello Joe.
  Hello Joe and Billy.
  $
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment