Multi-Dispatch

 view release on metacpan or  search on metacpan

lib/Multi/Dispatch.pm  view on Meta::CPAN

            die "Empty event array";
        }
        else {
            die "Unknown command: $cmd";
        }
    }

This code uses a single multisub with a signature, to ensure that it receives
the correct kind of argument. But then it unpacks the contents of that argument
"manually", and determines what action to take by explicitly deciphering the
structure of the argument in a cascaded S<C<if>-C<elsif>> sequence...all in that
single variant.

Avoiding that kind of all-in-one hand-coded infrastructure is the entire
reason for having multiple dispatch, so it won't come as much of a surprise
that Multi::Dispatch offers a much cleaner way of achieving the same goal:

    multi handle( ['delete',        $ID]       ) { _delete_ID($ID)             }
    multi handle( ['insert', $data, $ID]       ) { _insert_ID($ID, $data)      }
    multi handle( ['report', $ID, $fh=*STDOUT] ) { print {$fh} _get_ID($ID)    }
    multi handle( [ ]                          ) { die "Empty event array"     }

lib/Multi/Dispatch.pm  view on Meta::CPAN

            die "Unknown command: $event->{cmd}";
        }
        else {
            die "Not a valid event";
        }
    }

While this is a arguably little cleaner than the array-based version,
and certainly a lot safer I<(are you B<sure> all the array indexes
were correct in the array-based version???)>, it still suffers from
the "all-in-one-cascade" problem.

Fortunately, Multi::Dispatch can also destructure hashref parameters,
allowing them to be specified as destructuring anonymous hashes:

    multi handle( { cmd=>'delete', ID=>$ID }                    ) {...}
    multi handle( { cmd=>'insert', ID=>$ID, data=>$data }       ) {...}
    multi handle( { cmd=>'report', ID=>$ID, fh=>$fh = *STDOUT } ) {...}
    multi handle( { }                                           ) {...}
    multi handle( { cmd=>$cmd, % }                              ) {...}



( run in 0.410 second using v1.01-cache-2.11-cpan-3cd7ad12f66 )