Listing 4.
Multimethods + subroutines = overloading
Multiple Dispatch in Perl
The Perl Journal, Spring 2000
 
my %table;
   
sub debug {
    my $argtype = ref($_[0]);
    my $handler = $table{$argtype};
    if (!$handler) {
        foreach my $anc ( ancestors($argtype) ) {
            $handler = $table{$anc};
            next unless $handler;
            $table{$argtype} = $handler;
            last;
        }
    }
    die "No handler defined for $arg" unless $handler;
    $handler->(@_);
}
   
sub debug_for {
    my ($argtype,$handler) = @_;
    $table{$argtype} = $handler;
}

debug_for ""
    => sub { print "Scalar value is: $_[0]\n" };

debug_for "Window"
    => sub { print "Reference to Window: $_[0]->{_id}\n" };

debug_for "SCALAR"
    => sub { print "Scalar reference to value: ${$_[0]}\n" };

debug_for "ARRAY"
    => sub { print "ARRAY:\n"; 
             foreach ( @{$_[0]} )
                 { print "ELEMENT: "; debug($_) }
           };
   
debug_for "HASH"
    => sub { print "HASH:\n"; 
             foreach ( keys %{$_[0]} )
                 { print "KEY: "; debug($_);
                   print "VAL: "; debug($_[0]->{$_}); }
           };

debug_for "CODE"
    => sub { print "CODE\n" };