Sub::SmartMatch - Use smart matching to define multi subs
use Sub::SmartMatch; use SmartMatch::Sugar qw(any); # variants will be tried in a given/when # clause in the order they are defined multi fact => [ 0 ], sub { 1 }; multi fact => any, sub { my $n = shift; return $n * fact($n - 1); }
This module provides Haskell/ML style subroutine variants based on Perl's smartmatch operator.
This doesn't do argument binding, just value matching.
To define methods use SmartMatch::Sugar's object test:
SmartMatch::Sugar
object
multi new [ class ] => sub { # invoked as a class method } multi new [ object ] => sub { # invoked as an object method # this should clone, i guess }
This marks this case for exact matching. This means that it will match on \@_, not on the slice <[ @_[0 .. $#$case] ]>.
\@_
<[ @_[0 .. $#$case] ]
This only applies to cases which are array references themselves.
Define a variant for the sub name $name.
$name
$case will be smartmatched against an array reference of the arguments to the subroutine.
$case
As a special case to allow variable arguments at the end of the list, if $case is an array reference it will only be matched against the slice of @_ with the corresponding number of elements, not all of @_. Use exactly to do a match on all of @_. This does not apply to an empty array (otherwise that would always match, instead of matching empty arrays).
@_
exactly
Define the default for a multi sub. This variant is always tried last if no other variant matched.
default
Define a multi sub in one go.
def_multi foo => ( $case => $body, ... => ..., default => $default, );
SmartMatch::Sugar, Sub::PatternMatch, perlsyn, Class::Multimethods::Pure
This module is maintained using Darcs. You can get the latest version from http://nothingmuch.woobling.org/code, and use darcs send to commit changes.
darcs send
Yuval Kogman <nothingmuch@woobling.org>
Copyright (c) 2008 Yuval Kogman. All rights reserved This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Sub::SmartMatch, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sub::SmartMatch
CPAN shell
perl -MCPAN -e shell install Sub::SmartMatch
For more information on module installation, please visit the detailed CPAN module installation guide.