view release on metacpan or search on metacpan
CONTRIBUTING view on Meta::CPAN
NAME
CONTRIBUTING
DESCRIPTION
If you're reading this document, that means you might be thinking about
helping me out with this project. Thanks!
Here's some ways you could help out:
* Bug reports
Found a bug? Great! (Well, not so great I suppose.)
The place to report them is <https://rt.cpan.org/>. Don't e-mail me
about it, as your e-mail is more than likely to get lost amongst the
spam.
An example script clearly demonstrating the bug (preferably written
using Test::More) would be greatly appreciated.
* Patches
If you've found a bug and written a fix for it, even better!
Generally speaking you should check out the latest copy of the code
from the source repository rather than using the CPAN distribution.
The file META.yml should contain a link to the source repository. If
not, then try <https://github.com/tobyink> or submit a bug report.
(As far as I'm concerned the lack of a link is a bug.) Many of my
distributions are also mirrored at <https://bitbucket.org/tobyink>.
To submit the patch, do a pull request on GitHub or Bitbucket, or
attach a diff file to a bug report. Unless otherwise stated, I'll
assume that your contributions are licensed under the same terms as
the rest of the project.
(If using git, feel free to work in a branch. For Mercurial, I'd
prefer bookmarks within the default branch.)
* Documentation
If there's anything unclear in the documentation, please submit this
as a bug report or patch as above.
Non-toy example scripts that I can bundle would also be appreciated.
* Translation
Translations of documentation would be welcome.
For translations of error messages and other strings embedded in the
code, check with me first. Sometimes the English strings may not in
a stable state, so it would be a waste of time translating them.
Coding Style
I tend to write using something approximating the Allman style, using
tabs for indentation and Unix-style line breaks.
* <http://en.wikipedia.org/wiki/Indent_style#Allman_style>
* <http://www.derkarl.org/why_to_tabs.html>
I nominally encode all source files as UTF-8, though in practice most of
them use a 7-bit-safe ASCII-compatible subset of UTF-8.
AUTHOR
Toby Inkster <tobyink@cpan.org>.
COPYRIGHT AND LICENCE
Copyright (c) 2012-2014 by Toby Inkster.
CONTRIBUTING is available under three different licences permitting its
redistribution: the CC-BY-SA_UK-2.0 licence, plus the same licences as
Perl itself, which is distributed under the GNU General Public Licence
version 1, and the Artistic Licence.
This file is licensed under the Creative Commons Attribution-ShareAlike
2.0 UK: England & Wales License. To view a copy of this license, visit
<http://creativecommons.org/licenses/by-sa/2.0/uk/>.
This file is free software; you can redistribute it and/or modify it
under the same terms as the Perl 5 programming language system itself.
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Smart-Dispatch
Upstream-Contact: TOBYINK <tobyink@cpan.org> and Toby Inkster <tobyink@cpan.org>
Source: https://metacpan.org/release/Smart-Dispatch
Files: Changes
META.json
META.yml
dist.ini
doap.ttl
t/04exists.t
Copyright: Copyright 2014 Toby Inkster.
License: GPL-1.0+ or Artistic-1.0
Files: CONTRIBUTING
INSTALL
LICENSE
examples/calculator.pl
examples/tour-de-force.pl
examples/use-syntax.pl
Copyright: Unknown
License: Unknown
Files: README
lib/Smart/Dispatch.pm
lib/Smart/Dispatch/Match.pm
lib/Smart/Dispatch/Table.pm
lib/Syntax/Feature/Dispatcher.pm
Copyright: This software is copyright (c) 2012 by Toby Inkster.
License: GPL-1.0+ or Artistic-1.0
Files: t/01basic.t
t/02dispatcher.t
t/03overloading.t
t/05subclassing.t
Copyright: Copyright 2012 Toby Inkster.
License: GPL-1.0+ or Artistic-1.0
Files: COPYRIGHT
CREDITS
SIGNATURE
Copyright: None
License: public-domain
Files: Makefile.PL
Copyright: Copyright 2013 Toby Inkster.
License: GPL-1.0+ or Artistic-1.0
License: Artistic-1.0
This software is Copyright (c) 2014 by the copyright holder(s).
This is free software, licensed under:
The Artistic License 1.0
License: GPL-1.0
This software is Copyright (c) 2014 by the copyright holder(s).
This is free software, licensed under:
The GNU General Public License, Version 1, February 1989
Maintainer:
- TOBYINK <tobyink@cpan.org>
- Toby Inkster <tobyink@cpan.org>
Thanks:
- ANDK <andk@cpan.org>
Smart-Dispatch
==============
Created: 2012-02-20
Home page: <https://metacpan.org/release/Smart-Dispatch>
Bug tracker: <http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch>
Maintainer: Toby Inkster <tobyink@cpan.org>
0.006 2014-09-16
[ Packaging ]
- Add repo link.
0.005 2014-09-10
[ Packaging ]
- Switch to Dist::Inkt.
0.004 2012-12-03
[ Bug Fixes ]
- Remove traces of Any::Moose from test cases.
Fixes RT#81658.
ANDK++
<https://rt.cpan.org/Ticket/Display.html?id=81658>
0.003 2012-11-05 Remember, remember
- Updated: Port from Any::Mouse to Moo.
- Use namespace::clean to lexicalize exported subs.
0.002 2012-02-20
- Added: Syntax::Feature::Dispatcher
0.001 2012-02-20 Initial release
Installing Smart-Dispatch should be straightforward.
INSTALLATION WITH CPANMINUS
If you have cpanm, you only need one line:
% cpanm Smart::Dispatch
If you are installing into a system-wide directory, you may need to pass
the "-S" flag to cpanm, which uses sudo to install the module:
% cpanm -S Smart::Dispatch
INSTALLATION WITH THE CPAN SHELL
Alternatively, if your CPAN shell is set up, you should just be able to
do:
% cpan Smart::Dispatch
MANUAL INSTALLATION
As a last resort, you can manually install it. Download the tarball and
unpack it.
Consult the file META.json for a list of pre-requisites. Install these
first.
To build Smart-Dispatch:
% perl Makefile.PL
% make && make test
Then install it:
% make install
If you are installing into a system-wide directory, you may need to run:
% sudo make install
This software is copyright (c) 2014 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
Terms of the Perl programming language system itself
a) the GNU General Public License as published by the Free
Software Foundation; either version 1, or (at your option) any
later version, or
b) the "Artistic License"
--- The GNU General Public License, Version 1, February 1989 ---
This software is Copyright (c) 2014 by Toby Inkster.
This is free software, licensed under:
The GNU General Public License, Version 1, February 1989
GNU GENERAL PUBLIC LICENSE
Version 1, February 1989
Copyright (C) 1989 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The license agreements of most software companies try to keep users
at the mercy of those companies. By contrast, our General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. The
General Public License applies to the Free Software Foundation's
software and to any other program whose authors commit to using it.
You can use it for your programs, too.
When we speak of free software, we are referring to freedom, not
price. Specifically, the General Public License is designed to make
sure that you have the freedom to give away or sell copies of free
software, that you receive source code or can get it if you want it,
that you can change the software or use pieces of it in new free
programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of a such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must tell them their rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any program or other work which
contains a notice placed by the copyright holder saying it may be
distributed under the terms of this General Public License. The
"Program", below, refers to any such program or work, and a "work based
on the Program" means either the Program or any work containing the
Program or a portion of it, either verbatim or with modifications. Each
licensee is addressed as "you".
1. You may copy and distribute verbatim copies of the Program's source
code as you receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice and
disclaimer of warranty; keep intact all the notices that refer to this
General Public License and to the absence of any warranty; and give any
other recipients of the Program a copy of this General Public License
along with the Program. You may charge a fee for the physical act of
transferring a copy.
2. You may modify your copy or copies of the Program or any portion of
it, and copy and distribute such modifications under the terms of Paragraph
1 above, provided that you also do the following:
a) cause the modified files to carry prominent notices stating that
you changed the files and the date of any change; and
b) cause the whole of any work that you distribute or publish, that
in whole or in part contains the Program or any part thereof, either
with or without modifications, to be licensed at no charge to all
third parties under the terms of this General Public License (except
that you may choose to grant warranty protection to some or all
third parties, at your option).
c) If the modified program normally reads commands interactively when
run, you must cause it, when started running for such interactive use
in the simplest and most usual way, to print or display an
announcement including an appropriate copyright notice and a notice
that there is no warranty (or else, saying that you provide a
warranty) and that users may redistribute the program under these
conditions, and telling the user how to view a copy of this General
Public License.
d) You may charge a fee for the physical act of transferring a
copy, and you may at your option offer warranty protection in
exchange for a fee.
Mere aggregation of another independent work with the Program (or its
derivative) on a volume of a storage or distribution medium does not bring
the other work under the scope of these terms.
3. You may copy and distribute the Program (or a portion or derivative of
it, under Paragraph 2) in object code or executable form under the terms of
Paragraphs 1 and 2 above provided that you also do one of the following:
a) accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of
Paragraphs 1 and 2 above; or,
b) accompany it with a written offer, valid for at least three
years, to give any third party free (except for a nominal charge
for the cost of distribution) a complete machine-readable copy of the
corresponding source code, to be distributed under the terms of
Paragraphs 1 and 2 above; or,
c) accompany it with the information you received as to where the
corresponding source code may be obtained. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form alone.)
Source code for a work means the preferred form of the work for making
modifications to it. For an executable file, complete source code means
all the source code for all modules it contains; but, as a special
exception, it need not include source code for modules which are standard
libraries that accompany the operating system on which the executable
file runs, or for standard header files or definitions files that
accompany that operating system.
4. You may not copy, modify, sublicense, distribute or transfer the
Program except as expressly provided under this General Public License.
Any attempt otherwise to copy, modify, sublicense, distribute or transfer
the Program is void, and will automatically terminate your rights to use
the Program under this License. However, parties who have received
copies, or rights to use copies, from you under this General Public
License will not have their licenses terminated so long as such parties
remain in full compliance.
5. By copying, distributing or modifying the Program (or any work based
on the Program) you indicate your acceptance of this license to do so,
and all its terms and conditions.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the original
licensor to copy, distribute or modify the Program subject to these
terms and conditions. You may not impose any further restrictions on the
recipients' exercise of the rights granted herein.
7. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of the license which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
the license, you may choose any version ever published by the Free Software
Foundation.
8. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
Appendix: How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to humanity, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively convey
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 19yy <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 1, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) 19xx name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the
appropriate parts of the General Public License. Of course, the
commands you use may be called something other than `show w' and `show
c'; they could even be mouse-clicks or menu items--whatever suits your
program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
program `Gnomovision' (a program to direct compilers to make passes
at assemblers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
That's all there is to it!
--- The Artistic License 1.0 ---
This software is Copyright (c) 2014 by Toby Inkster.
This is free software, licensed under:
The Artistic License 1.0
The Artistic License
Preamble
The intent of this document is to state the conditions under which a Package
may be copied, such that the Copyright Holder maintains some semblance of
artistic control over the development of the package, while giving the users of
the package the right to use and distribute the Package in a more-or-less
customary fashion, plus the right to make reasonable modifications.
Definitions:
- "Package" refers to the collection of files distributed by the Copyright
Holder, and derivatives of that collection of files created through
textual modification.
- "Standard Version" refers to such a Package if it has not been modified,
or has been modified in accordance with the wishes of the Copyright
Holder.
- "Copyright Holder" is whoever is named in the copyright or copyrights for
the package.
- "You" is you, if you're thinking about copying or distributing this Package.
- "Reasonable copying fee" is whatever you can justify on the basis of media
cost, duplication charges, time of people involved, and so on. (You will
not be required to justify it to the Copyright Holder, but only to the
computing community at large as a market that must bear the fee.)
- "Freely Available" means that no fee is charged for the item itself, though
there may be fees involved in handling the item. It also means that
recipients of the item may redistribute it under the same conditions they
received it.
1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you
duplicate all of the original copyright notices and associated disclaimers.
2. You may apply bug fixes, portability fixes and other modifications derived
from the Public Domain or from the Copyright Holder. A Package modified in such
a way shall still be considered the Standard Version.
3. You may otherwise modify your copy of this Package in any way, provided that
you insert a prominent notice in each changed file stating how and when you
changed that file, and provided that you do at least ONE of the following:
a) place your modifications in the Public Domain or otherwise make them
Freely Available, such as by posting said modifications to Usenet or an
equivalent medium, or placing the modifications on a major archive site
such as ftp.uu.net, or by allowing the Copyright Holder to include your
modifications in the Standard Version of the Package.
b) use the modified Package only within your corporation or organization.
c) rename any non-standard executables so the names do not conflict with
standard executables, which must also be provided, and provide a separate
manual page for each non-standard executable that clearly documents how it
differs from the Standard Version.
d) make other distribution arrangements with the Copyright Holder.
4. You may distribute the programs of this Package in object code or executable
form, provided that you do at least ONE of the following:
a) distribute a Standard Version of the executables and library files,
together with instructions (in the manual page or equivalent) on where to
get the Standard Version.
b) accompany the distribution with the machine-readable source of the Package
with your modifications.
c) accompany any non-standard executables with their corresponding Standard
Version executables, giving the non-standard executables non-standard
names, and clearly documenting the differences in manual pages (or
equivalent), together with instructions on where to get the Standard
Version.
d) make other distribution arrangements with the Copyright Holder.
5. You may charge a reasonable copying fee for any distribution of this
Package. You may charge any fee you choose for support of this Package. You
may not charge a fee for this Package itself. However, you may distribute this
Package in aggregate with other (possibly commercial) programs as part of a
larger (possibly commercial) software distribution provided that you do not
advertise this Package as a product of your own.
6. The scripts and library files supplied as input to or produced as output
from the programs of this Package do not automatically fall under the copyright
of this Package, but belong to whomever generated them, and may be sold
commercially, and may be aggregated with this Package.
7. C or perl subroutines supplied by you and linked into this Package shall not
be considered part of this Package.
8. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.
9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
The End
CONTRIBUTING
COPYRIGHT
CREDITS
Changes
INSTALL
LICENSE
MANIFEST
META.json
META.yml
Makefile.PL
README
SIGNATURE
dist.ini
doap.ttl
examples/calculator.pl
examples/tour-de-force.pl
examples/use-syntax.pl
lib/Smart/Dispatch.pm
lib/Smart/Dispatch/Match.pm
lib/Smart/Dispatch/Table.pm
lib/Syntax/Feature/Dispatcher.pm
t/01basic.t
t/02dispatcher.t
t/03overloading.t
t/04exists.t
t/05subclassing.t
{
"abstract" : "first-class switch statements",
"author" : [
"Toby Inkster <tobyink@cpan.org>",
"TOBYINK <tobyink@cpan.org>"
],
"dynamic_config" : 0,
"generated_by" : "Dist::Inkt::Profile::TOBYINK version 0.021, CPAN::Meta::Converter version 2.140640",
"keywords" : [],
"license" : [
"perl_5"
],
"meta-spec" : {
"url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec",
"version" : "2"
},
"name" : "Smart-Dispatch",
"no_index" : {
"directory" : [
"eg",
"examples",
"inc",
"t",
"xt"
]
},
"optional_features" : {},
"prereqs" : {
"configure" : {
"requires" : {
"ExtUtils::MakeMaker" : "6.17"
}
},
"runtime" : {
"requires" : {
"Moo" : "0",
"Sub::Exporter" : "0",
"namespace::clean" : "0",
"perl" : "5.010"
}
},
"test" : {
"requires" : {
"Test::More" : "0.61",
"Test::Warn" : "0"
}
}
},
"provides" : {
"Smart::Dispatch" : {
"file" : "lib/Smart/Dispatch.pm",
"version" : "0.006"
},
"Smart::Dispatch::Match" : {
"file" : "lib/Smart/Dispatch/Match.pm",
"version" : "0.006"
},
"Smart::Dispatch::Table" : {
"file" : "lib/Smart/Dispatch/Table.pm",
"version" : "0.006"
},
"Syntax::Feature::Dispatcher" : {
"file" : "lib/Syntax/Feature/Dispatcher.pm",
"version" : "0.006"
}
},
"release_status" : "stable",
"resources" : {
"bugtracker" : {
"web" : "http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch"
},
"homepage" : "https://metacpan.org/release/Smart-Dispatch",
"license" : [
"http://dev.perl.org/licenses/"
],
"repository" : {
"type" : "git",
"url" : "git://github.com/tobyink/p5-smart-dispatch.git",
"web" : "https://github.com/tobyink/p5-smart-dispatch"
},
"x_identifier" : "http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/project"
},
"version" : "0.006"
}
---
abstract: 'first-class switch statements'
author:
- 'Toby Inkster <tobyink@cpan.org>'
- 'TOBYINK <tobyink@cpan.org>'
build_requires:
Test::More: '0.61'
Test::Warn: '0'
configure_requires:
ExtUtils::MakeMaker: '6.17'
dynamic_config: 0
generated_by: 'Dist::Inkt::Profile::TOBYINK version 0.021, CPAN::Meta::Converter version 2.140640'
keywords: []
license: perl
meta-spec:
url: http://module-build.sourceforge.net/META-spec-v1.4.html
version: '1.4'
name: Smart-Dispatch
no_index:
directory:
- eg
- examples
- inc
- t
- xt
optional_features: {}
provides:
Smart::Dispatch:
file: lib/Smart/Dispatch.pm
version: '0.006'
Smart::Dispatch::Match:
file: lib/Smart/Dispatch/Match.pm
version: '0.006'
Smart::Dispatch::Table:
file: lib/Smart/Dispatch/Table.pm
version: '0.006'
Syntax::Feature::Dispatcher:
file: lib/Syntax/Feature/Dispatcher.pm
version: '0.006'
requires:
Moo: '0'
Sub::Exporter: '0'
namespace::clean: '0'
perl: '5.010'
resources:
Identifier: http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/project
bugtracker: http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch
homepage: https://metacpan.org/release/Smart-Dispatch
license: http://dev.perl.org/licenses/
repository: git://github.com/tobyink/p5-smart-dispatch.git
version: '0.006'
Makefile.PL view on Meta::CPAN
use strict;
use ExtUtils::MakeMaker 6.17;
my $EUMM = eval( $ExtUtils::MakeMaker::VERSION );
my $meta = {
"abstract" => "first-class switch statements",
"author" => [
"Toby Inkster <tobyink\@cpan.org>",
"TOBYINK <tobyink\@cpan.org>",
],
"dynamic_config" => 0,
"generated_by" => "Dist::Inkt::Profile::TOBYINK version 0.021, CPAN::Meta::Converter version 2.140640",
"keywords" => [],
"license" => ["perl_5"],
"meta-spec" => {
url => "http://search.cpan.org/perldoc?CPAN::Meta::Spec",
version => 2,
},
"name" => "Smart-Dispatch",
"no_index" => { directory => ["eg", "examples", "inc", "t", "xt"] },
"prereqs" => {
configure => { requires => { "ExtUtils::MakeMaker" => 6.17 } },
runtime => {
requires => {
"Moo" => 0,
"namespace::clean" => 0,
"perl" => "5.010",
"Sub::Exporter" => 0,
},
},
test => { requires => { "Test::More" => 0.61, "Test::Warn" => 0 } },
},
"provides" => {
"Smart::Dispatch" => { file => "lib/Smart/Dispatch.pm", version => 0.006 },
"Smart::Dispatch::Match" => { file => "lib/Smart/Dispatch/Match.pm", version => 0.006 },
"Smart::Dispatch::Table" => { file => "lib/Smart/Dispatch/Table.pm", version => 0.006 },
"Syntax::Feature::Dispatcher" => { file => "lib/Syntax/Feature/Dispatcher.pm", version => 0.006 },
},
"release_status" => "stable",
"resources" => {
bugtracker => {
web => "http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch",
},
homepage => "https://metacpan.org/release/Smart-Dispatch",
license => ["http://dev.perl.org/licenses/"],
repository => {
type => "git",
url => "git://github.com/tobyink/p5-smart-dispatch.git",
web => "https://github.com/tobyink/p5-smart-dispatch",
},
x_identifier => "http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/project",
},
"version" => 0.006,
};
my %dynamic_config;
my %WriteMakefileArgs = (
ABSTRACT => $meta->{abstract},
AUTHOR => ($EUMM >= 6.5702 ? $meta->{author} : $meta->{author}[0]),
DISTNAME => $meta->{name},
VERSION => $meta->{version},
EXE_FILES => [ map $_->{file}, values %{ $meta->{x_provides_scripts} || {} } ],
NAME => do { my $n = $meta->{name}; $n =~ s/-/::/g; $n },
test => { TESTS => "t/*.t" },
%dynamic_config,
);
$WriteMakefileArgs{LICENSE} = $meta->{license}[0] if $EUMM >= 6.3001;
sub deps
{
my %r;
for my $stage (@_)
{
for my $dep (keys %{$meta->{prereqs}{$stage}{requires}})
{
next if $dep eq 'perl';
my $ver = $meta->{prereqs}{$stage}{requires}{$dep};
$r{$dep} = $ver if !exists($r{$dep}) || $ver >= $r{$dep};
}
}
\%r;
}
my ($build_requires, $configure_requires, $runtime_requires, $test_requires);
if ($EUMM >= 6.6303)
{
$WriteMakefileArgs{BUILD_REQUIRES} ||= deps('build');
$WriteMakefileArgs{CONFIGURE_REQUIRES} ||= deps('configure');
$WriteMakefileArgs{TEST_REQUIRES} ||= deps('test');
$WriteMakefileArgs{PREREQ_PM} ||= deps('runtime');
}
elsif ($EUMM >= 6.5503)
{
$WriteMakefileArgs{BUILD_REQUIRES} ||= deps('build', 'test');
$WriteMakefileArgs{CONFIGURE_REQUIRES} ||= deps('configure');
$WriteMakefileArgs{PREREQ_PM} ||= deps('runtime');
}
elsif ($EUMM >= 6.52)
{
$WriteMakefileArgs{CONFIGURE_REQUIRES} ||= deps('configure');
$WriteMakefileArgs{PREREQ_PM} ||= deps('runtime', 'build', 'test');
}
else
{
$WriteMakefileArgs{PREREQ_PM} ||= deps('configure', 'build', 'test', 'runtime');
}
{
my ($minperl) = reverse sort(
grep defined && /^[0-9]+(\.[0-9]+)?$/,
map $meta->{prereqs}{$_}{requires}{perl},
qw( configure build runtime )
);
if (defined($minperl))
{
die "Installing $meta->{name} requires Perl >= $minperl"
unless $] >= $minperl;
$WriteMakefileArgs{MIN_PERL_VERSION} ||= $minperl
if $EUMM >= 6.48;
}
}
sub FixMakefile
{
return unless -d 'inc';
my $file = shift;
local *MAKEFILE;
open MAKEFILE, "< $file" or die "FixMakefile: Couldn't open $file: $!; bailing out";
my $makefile = do { local $/; <MAKEFILE> };
close MAKEFILE or die $!;
$makefile =~ s/\b(test_harness\(\$\(TEST_VERBOSE\), )/$1'inc', /;
$makefile =~ s/( -I\$\(INST_ARCHLIB\))/ -Iinc$1/g;
$makefile =~ s/( "-I\$\(INST_LIB\)")/ "-Iinc"$1/g;
$makefile =~ s/^(FULLPERL = .*)/$1 "-Iinc"/m;
$makefile =~ s/^(PERL = .*)/$1 "-Iinc"/m;
open MAKEFILE, "> $file" or die "FixMakefile: Couldn't open $file: $!; bailing out";
print MAKEFILE $makefile or die $!;
close MAKEFILE or die $!;
}
my $mm = WriteMakefile(%WriteMakefileArgs);
FixMakefile($mm->{FIRST_MAKEFILE} || 'Makefile');
exit(0);
NAME
Smart::Dispatch - first-class switch statements
SYNOPSIS
use Smart::Dispatch;
my $given = dispatcher {
match qr{ ^[A-J] }ix, dispatch { "Volume 1" };
match qr{ ^[K-Z] }ix, dispatch { "Volume 2" };
otherwise failover { Carp::croak "unexpected surname" };
};
my $surname = "Inkster";
say $surname, " is in ", $dispatch->($surname), " of the phone book.";
DESCRIPTION
People have been using dispatch tables for years. They work along the
lines of:
my $thing = get_foo_or_bar();
my %dispatch = (
foo => sub { ... },
bar => sub { ... },
);
$dispatch{$thing}->();
Dispatch tables are often more elegant than long groups of
`if`/`elsif`/`else` statements, but they do have drawbacks. Consider how
you'd change the example above to deal with $thing being not just "foo" or
"bar", but adding all integers to the allowed values.
Perl 5.10 introduced smart match and the `given` block. This allows stuff
like:
my $thing = get_foo_or_bar();
given ($thing)
{
when ("foo") { ... }
when ("bar") { ... }
when (looks_like_number($_)) { ... }
}
The conditions in `when` clauses can be arbirarily complex tests, and
default to comparisons using the smart match operator. This is far more
flexible.
`given` blocks do have some drawbacks over dispatch tables though. A
dispatch table is a first class object - you can put a reference to it in
a variable, and pass that reference as an argument to functions. You can
check to see whether a dispatch table contains particular entries:
if ($dispatch{"foo"}) # dispatch table can deal with $thing="foo"
If passed a reference to an existing dispatch table, you can easily add
entries to it, or remove entries from it.
Smart::Dispatch is an attempt to combine some of the more useful features
of `given` with dispatch tables.
Building a Dispatch Table
All the keywords used a build a dispatch table are lexical subs, which
means that you can import them into a particular code block and they will
not be available outside that block.
`dispatcher { CODE }`
A dispatch table is built using the `dispatcher` function which takes a
single block argument. This block will typically consist of a number of
`match` statements, though you can theoretically put anything you want
inside it. (The code is run just once, when the dispatch table is being
built, and is called in void context.)
my $dispatch_table = dispatcher { ... };
The return value is an Smart::Dispatch::Table object.
`match $test, %args`
The `match` function adds a single entry to the current dispatch table.
The entry is a Smart::Dispatch::Match object.
The $test argument is the trigger for dispatching to that particular entry
in the table. It's like the contents of `when(...)` in a `given` block. It
is used as the right hand argument to a smart match operation (see
perlop), so it can be a string/numeric constant, `undef`, a `qr/.../`
quoted regular expression, or a coderef, or an reference to an array
containing any of the above. (There are other possibilities too, though
they are somewhat obscure.)
The hash of other arguments is passed to the constructor of
Smart::Dispatch::Match.
`dispatch { CODE }`
This introduces the code to run when a match has been successful. It is
used as follows:
my $dispatch_table = dispatcher {
match "foo", dispatch { "Monkey" };
match "bar", dispatch { my $x = get_simian(); return $x };
};
Actually the above is just syntactic sugar for
my $dispatch_table = dispatcher {
match "foo", 'dispatch' => sub { "Monkey" };
match "bar", 'dispatch' => sub { my $x = get_simian(); return $x };
};
So the only thing `dispatch` is doing is depositing a coderef into the
%args hash of `match`.
`value => $value`
In the case of the "Monkey" bit above, it's actually a little wasteful to
define a coderef (and run it when we do the dispatching later on) just to
return a constant string, so in this case we can use the 'value' argument
for `match`, to provide a slight optimization:
my $dispatch_table = dispatcher {
match "foo", value => "Monkey";
match "bar", dispatch { my $x = get_simian(); return $x };
};
Note that `value` is not a function. It's just a named argument for
`match`. Nothing much magic is going on.
`match_using { CODE } %args`
`match_using` is exactly like `match` but declared with a coderef
prototype (see perlsub). That is, it just gives you syntactic sugar for
the case where $test is a coderef. The following are equivalent:
`match_using { $_ < 5 } dispatch { say "$_ is low" };`
`match sub { $_ < 5 }, 'dispatch' => sub { say "$_ is low" };`
`otherwise %args`
`otherwise` is equivalent to `default` in `given` blocks, or `else` in
`if` blocks. It matches all other cases, and must thus be the last match
declared.
Again this is really just syntactic sugar. The following are equivalent:
`otherwise dispatch { undef };`
`match sub { 1 }, 'is_unconditional' => 1, 'dispatch' => sub { undef };`
Note that `otherwise` explicitly marks the match as an "unconditional"
match. This allows Smart::Dispatch to complain if `otherwise` is not the
last match in a dispatch table. And it helps when you try to combine
multiple dispatch tables to know which is the "otherwise" match.
`failover { CODE }`
This is roughly the same as `dispatch`, but is intended for marking
dispatches that can be regarded as failures:
my $roman = dispatcher {
match qr{\D}, failover { croak "non-numeric" };
match [1..3], dispatch { "I" x $_ };
match 4, value => 'IV';
match [5..8], dispatch { 'V'.('I' x ($_-5)) };
match 9, value => 'IX';
match 10, value => 'X';
otherwise failover { croak "out of range" };
};
In terms of actually dispatching from the dispatch table, failovers work
exactly the same as any other dispatches. However, because the dispatch
table knows which matches are successes and which are failures, this
information can be queried.
It should be no surprise by now that the `failover` function is just
syntactic sugar, and the same effect can be achieved without it. The
following are equivalent:
`match $test, failover {...};`
`match $test, 'is_failover' => 1, 'dispatch' => sub {...};`
Using a Dispatch Table
OK, so now you know how to build a dispatch table, but once we've got one,
how can we use it?
Dispatch tables, although they are not coderefs, overload `&{}`, which
means they can be called like coderefs.
my $biological_sex = dispatcher {
match 'XX', dispatch { 'Female' };
match ['XY', 'YX'], dispatch { 'Male' };
otherwise failover { '????' };
};
my $sex_chromosomes = 'XY';
say "I am a ", $biological_sex->($sex_chromosomes);
The above will say "I am a Male".
Note that the dispatch and failover subs here are pretty boring (we could
have just used `<value`>), but any arbitrary Perl function is allowed.
Perl functions of course accept argument lists. Any argument list passed
into the dispatch table will be passed on to the dispatched function.
my $biological_sex = dispatcher {
match 'XX',
dispatch { $_[1] eq 'fr' ? 'Femelle' : 'Female' };
match ['XY', 'YX'],
dispatch { $_[1] eq 'fr' ? 'Male' : 'Male' };
otherwise
failover { '????' };
};
my $sex_chromosomes = 'XX';
say "I am a ", $biological_sex->($sex_chromosomes, 'en');
say "Je suis ", $biological_sex->($sex_chromosomes, 'fr');
Note that within `match_using`, `dispatch` and `failover` blocks, the
value being matched is available in the variable $_. The following match
demonstrates this:
match_using { $_ < 5 } dispatch { say "$_ is low" }
It is possible to check whether a dispatch table is able to handle a
particular value.
my $sex_chromosomes = 'AA';
if ($biological_sex ~~ $sex_chromosomes)
{
say "Dispatch table cannot handle chromosomes $sex_chromosomes";
}
else
{
say $biological_sex->($sex_chromosomes);
}
This is where `failover` comes in. Failover matches are not considered
when determining whether a dispatch table is capable of handling a value.
Manipulating Dispatch Tables
If you have an existing dispatch table, it's possible to add more entries
to it. For this purpose, Smart::Dispatch overloads the `.=` and `+=`
operators.
my $more_sexes = dispatcher {
match 'XYY', dispatch { 'Supermale' };
match 'XXX', dispatch { 'Superfemale' };
};
$biological_sex .= $more_sexes;
The difference between the two operators is the priority is which matches
are tested.
my $match1 = dispatcher {
match 1, dispatch { 'One' };
};
We can add some more matches like this:
$match1 .= dispatcher {
match qr{^1}, dispatch { 'Leading one' };
};
When dispatching value "1", the result will still be "One", because the
added matches have lower priority than the original ones.
But if they are combined as:
$match += dispatcher {
match qr{^1}, dispatch { 'Leading one' };
};
Then when dispatching value "1", the result will be "Leading one" because
the newer matches are given higher priority.
It is also possible to use `.` and `+` in their non-assignment forms:
my $enormous_match = $big_match . $large_match . $mighty_match;
(Some future version may introduce the ability to do subtraction, but
there are difficulties with this concept. For now, if you want to do
subtraction, look at the internals of Smart::Dispatch::Table.)
If one or both dispatch tables contain an unconditional match
(`otherwise`), then these will be combined intelligently. The result will
only have one unconditional match (the higher priority one).
Import
By default Smart::Dispatch exports the following functions:
* `dispatch`
* `dispatcher`
* `failover`
* `match`
* `match_using`
* `otherwise`
It is possible to only import a subset of those:
use Smart::Dispatch qw/dispatcher match otherwise/;
As noted in the "Building a Dispatch Table" section, a minimal set of
functions is just `dispatcher` and `match`. All the others are just
syntactic sugar. If you just want those two, then you can do:
use Smart::Dispatch qw/:tiny/;
Smart::Dispatch uses Sub::Exporter which provides a dizzying array of cool
options, such as:
use Smart::Dispatch -all => { -prefix => 'sd_' };
which imports all the symbols but prefixed with "sd_".
use Smart::Dispatch
qw/dispatcher dispatch match/,
otherwise => { -as => 'last_resort' };
which renames "otherwise" to "last_resort".
If you've written subclasses of Smart::Dispatch::Table and
Smart::Dispatch::Match and you want Smart::Dispatch to use your
subclasses, then you can do this:
use Smart::Dispatch
qw/dispatcher dispatch match/,
otherwise => { -as => 'last_resort' },
class => {
table => 'My::Dispatch::Table',
match => 'My::Dispatch::Match',
};
Whatsmore, the `class` option can be set on a keyword-by-keyword basis for
`match`, `match_using` and `otherwise`.
use Smart::Dispatch
qw/dispatcher dispatch match/,
otherwise => {
-as => 'last_resort',
class => 'My::Other::Match',
},
class => {
table => 'My::Dispatch::Table',
match => 'My::Dispatch::Match',
};
Constants
* `DEFAULT_MATCH_CLASS`
* `DEFAULT_TABLE_CLASS`
Dispatch Table Internals
See Smart::Dispatch::Table and Smart::Dispatch::Match.
Note that this is an early release, so the internals are still likely to
change somewhat between versions. The function-based API should be fairly
steady though.
BUGS
Please report any bugs to
<http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch>.
SEE ALSO
"Switch statements" in perlsyn; Acme::Given::Hash.
<http://www.perlmonks.org/?node_id=954831>.
AUTHOR
Toby Inkster <tobyink@cpan.org>.
COPYRIGHT AND LICENCE
This software is copyright (c) 2012 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under the
same terms as the Perl 5 programming language system itself.
DISCLAIMER OF WARRANTIES
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
This file contains message digests of all files listed in MANIFEST,
signed via the Module::Signature module, version 0.73.
To verify the content in this distribution, first make sure you have
Module::Signature installed, then type:
% cpansign -v
It will check each file's integrity, as well as the signature's
validity. If "==> Signature verified OK! <==" is not displayed,
the distribution may already have been compromised, and you should
not run its Makefile.PL or Build.PL.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
SHA1 33317486c4fa2cf7fec85bf92ed38ac0f64233a0 CONTRIBUTING
SHA1 230769a588824fe72802769beef6466ce2bb86b1 COPYRIGHT
SHA1 f37aa2421026e562f16cc0c33348e107dd6d0d7c CREDITS
SHA1 873c78e839e29f798596aff02e370a7308e2617a Changes
SHA1 25d72f44372d7fd692b1acc4f49d28e67e23bc80 INSTALL
SHA1 34f5e12514b91055de4b164a1f2327ef5c30ba53 LICENSE
SHA1 def8e3ea643b87515e34411ff8f32cfb2728ab0c MANIFEST
SHA1 94648c34f813457224c57ba2a2b4dfde1b88e255 META.json
SHA1 c3cf639f0be9920622a0503bc687be3268500bc8 META.yml
SHA1 7c14bcdb64327e9dc47ecec015e053776ff31351 Makefile.PL
SHA1 5d5490639914afd1162838509cade1cbb38c075b README
SHA1 c27787fc5288c33b2fbe21f0522b2a13537eb38b dist.ini
SHA1 6cee95db3d5547ce88fb294d86a292a3d3ca9c1c doap.ttl
SHA1 e9c2a142c056ed5484fc478393ac6bb41c7a7778 examples/calculator.pl
SHA1 93352d4de5f9f22a16370daf0d333373434d55b7 examples/tour-de-force.pl
SHA1 3c54c02ea3dcdf5341c793b7a59106030e55728e examples/use-syntax.pl
SHA1 2e2200e1ecf110b8e347e769c0da22ce5d735512 lib/Smart/Dispatch.pm
SHA1 115fbb2953fd0f36d374d9f84e80723f9871883e lib/Smart/Dispatch/Match.pm
SHA1 ea39633fab8e4f403ac657be827aaae32a216227 lib/Smart/Dispatch/Table.pm
SHA1 0b82522921911d5fa99d48ca765900dfa24b1a53 lib/Syntax/Feature/Dispatcher.pm
SHA1 8843fc04330024e6443056d24d7a3004d6f7db62 t/01basic.t
SHA1 6ac0508ef34e64b6f2ff46167e373ea8bc2b0660 t/02dispatcher.t
SHA1 bd0a43dfa02546c608f9accec576507d19f29d1e t/03overloading.t
SHA1 5117b0284945a16d540d3fdb69bf244e92205057 t/04exists.t
SHA1 a7464fb63d5cae723dd5ca07506d6a0a8caeab43 t/05subclassing.t
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1
iEYEARECAAYFAlQYgqAACgkQzr+BKGoqfTl8SwCgkjehDkklIFf79kLIuqDj58NS
CqUAnRBzBAf0batjAmD/oofTiCYlT+5e
=rl+g
-----END PGP SIGNATURE-----
;;class='Dist::Inkt::Profile::TOBYINK'
;;name='Smart-Dispatch'
@prefix dc: <http://purl.org/dc/terms/> .
@prefix doap: <http://usefulinc.com/ns/doap#> .
@prefix doap-bugs: <http://ontologi.es/doap-bugs#> .
@prefix doap-changeset: <http://ontologi.es/doap-changeset#> .
@prefix doap-deps: <http://ontologi.es/doap-deps#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
<http://dev.perl.org/licenses/>
dc:title "the same terms as the perl 5 programming language system itself".
<http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/project>
a doap:Project;
dc:contributor <http://purl.org/NET/cpan-uri/person/tobyink>;
doap-deps:runtime-requirement [ doap-deps:on "perl 5.010"^^doap-deps:CpanId ], [ doap-deps:on "Moo"^^doap-deps:CpanId ], [ doap-deps:on "namespace::clean"^^doap-deps:CpanId ], [ doap-deps:on "Sub::Exporter"^^doap-deps:CpanId ];
doap-deps:test-requirement [ doap-deps:on "Test::Warn"^^doap-deps:CpanId ], [ doap-deps:on "Test::More 0.61"^^doap-deps:CpanId ];
doap:bug-database <http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch>;
doap:created "2012-02-20"^^xsd:date;
doap:download-page <https://metacpan.org/release/Smart-Dispatch>;
doap:homepage <https://metacpan.org/release/Smart-Dispatch>;
doap:license <http://dev.perl.org/licenses/>;
doap:maintainer [
a foaf:Person;
foaf:mbox <mailto:tobyink@cpan.org>;
foaf:name "Toby Inkster";
];
doap:name "Smart-Dispatch";
doap:programming-language "Perl";
doap:release <http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/v_0-001>, <http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/v_0-002>, <http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/v_0-003>, <http://purl.org/NET/cpan-uri/dist/Smart-Dispatc...
doap:repository [
a doap:GitRepository;
doap:browse <https://github.com/tobyink/p5-smart-dispatch>;
];
doap:shortdesc "first-class switch statements".
<http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/v_0-001>
a doap:Version;
rdfs:label "Initial release";
dc:identifier "Smart-Dispatch-0.001"^^xsd:string;
dc:issued "2012-02-20"^^xsd:date;
doap-changeset:released-by <http://purl.org/NET/cpan-uri/person/tobyink>;
doap:file-release <http://backpan.cpan.org/authors/id/T/TO/TOBYINK/Smart-Dispatch-0.001.tar.gz>;
doap:revision "0.001"^^xsd:string.
<http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/v_0-002>
a doap:Version;
dc:identifier "Smart-Dispatch-0.002"^^xsd:string;
dc:issued "2012-02-20"^^xsd:date;
doap-changeset:changeset [
doap-changeset:item [
a doap-changeset:Addition;
rdfs:label "Syntax::Feature::Dispatcher";
];
];
doap-changeset:released-by <http://purl.org/NET/cpan-uri/person/tobyink>;
doap:file-release <http://backpan.cpan.org/authors/id/T/TO/TOBYINK/Smart-Dispatch-0.002.tar.gz>;
doap:revision "0.002"^^xsd:string.
<http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/v_0-003>
a doap:Version;
rdfs:label "Remember, remember";
dc:identifier "Smart-Dispatch-0.003"^^xsd:string;
dc:issued "2012-11-05"^^xsd:date;
doap-changeset:changeset [
doap-changeset:item [
a doap-changeset:Update;
rdfs:label "Port from Any::Mouse to Moo.";
], [
a doap-changeset:Change;
rdfs:label "Use namespace::clean to lexicalize exported subs.";
];
];
doap-changeset:released-by <http://purl.org/NET/cpan-uri/person/tobyink>;
doap:file-release <http://backpan.cpan.org/authors/id/T/TO/TOBYINK/Smart-Dispatch-0.003.tar.gz>;
doap:revision "0.003"^^xsd:string.
<http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/v_0-004>
a doap:Version;
dc:identifier "Smart-Dispatch-0.004"^^xsd:string;
dc:issued "2012-12-03"^^xsd:date;
doap-changeset:changeset [
doap-changeset:item [
a doap-changeset:Bugfix;
rdfs:label "Remove traces of Any::Moose from test cases.";
doap-changeset:fixes <http://purl.org/NET/cpan-uri/rt/ticket/81658>;
doap-changeset:thanks <http://purl.org/NET/cpan-uri/person/andk>;
];
];
doap-changeset:released-by <http://purl.org/NET/cpan-uri/person/tobyink>;
doap:file-release <http://backpan.cpan.org/authors/id/T/TO/TOBYINK/Smart-Dispatch-0.004.tar.gz>;
doap:revision "0.004"^^xsd:string.
<http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/v_0-005>
a doap:Version;
dc:identifier "Smart-Dispatch-0.005"^^xsd:string;
dc:issued "2014-09-10"^^xsd:date;
doap-changeset:changeset [
doap-changeset:item [
a doap-changeset:Packaging;
rdfs:label "Switch to Dist::Inkt.";
];
];
doap-changeset:released-by <http://purl.org/NET/cpan-uri/person/tobyink>;
doap:file-release <http://backpan.cpan.org/authors/id/T/TO/TOBYINK/Smart-Dispatch-0.005.tar.gz>;
doap:revision "0.005"^^xsd:string.
<http://purl.org/NET/cpan-uri/dist/Smart-Dispatch/v_0-006>
a doap:Version;
dc:identifier "Smart-Dispatch-0.006"^^xsd:string;
dc:issued "2014-09-16"^^xsd:date;
doap-changeset:changeset [
doap-changeset:item [
a doap-changeset:Packaging;
rdfs:label "Add repo link.";
];
];
doap-changeset:released-by <http://purl.org/NET/cpan-uri/person/tobyink>;
doap:file-release <http://backpan.cpan.org/authors/id/T/TO/TOBYINK/Smart-Dispatch-0.006.tar.gz>;
doap:revision "0.006"^^xsd:string.
<http://purl.org/NET/cpan-uri/person/andk>
a foaf:Person;
foaf:nick "ANDK";
foaf:page <https://metacpan.org/author/ANDK>.
<http://purl.org/NET/cpan-uri/rt/ticket/81658>
a doap-bugs:Issue;
doap-bugs:id "81658"^^xsd:string;
doap-bugs:page <https://rt.cpan.org/Ticket/Display.html?id=81658>.
examples/calculator.pl view on Meta::CPAN
use feature qw( say );
use Smart::Dispatch;
{
my @stack;
my $eval = dispatcher {
match qr{\d+}, dispatch { push @stack, $_ };
match '+', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x + $y };
match '-', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x - $y };
match '*', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x * $y };
match '/', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x / $y };
match '%', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x % $y };
otherwise failover { warn "Unknown token '$_'\n" };
};
sub reverse_polish_calc {
@stack = ();
$eval->($_) for @_;
wantarray ? @stack : $stack[-1];
}
}
# ( 1 + ((2+3)*4) ) - 5 = 16
say reverse_polish_calc qw( 1 2 3 + 4 * + 5 - );
examples/tour-de-force.pl view on Meta::CPAN
use 5.010;
use strict;
use Smart::Dispatch;
sub action_1_to_999 {
"1 to 999";
}
my $dispatch = dispatcher {
match 0,
value => "Zero";
match [1..10],
dispatch { "Single digit $_" };
match 1_000,
dispatch { "1e3" };
match qr/^\d{4}/,
dispatch { "Over a thousand\n"};
match_using { $_ > 0 and $_ < 1000 }
dispatch \&action_1_to_999;
otherwise
failover { Carp::carp "failover"; "F" }
};
$dispatch += dispatcher { match 3, value => 'Trinity' };
say $dispatch->(0); # call dispatch table on value '0'
say $dispatch->(1); # call dispatch table on value '1'
say $dispatch->(3); # call dispatch table on value '3'
say $dispatch->(23); # guess!
# call dispatch table on '999999' but only if the dispatch table
# has an entry that covers value '-1'.
say $dispatch->(999999) if $dispatch ~~ -1;
# call dispatch table on '1000' but only if the dispatch table
# has an entry that covers value '4'.
say $dispatch->(1000) if $dispatch ~~ 4;
say (($dispatch ~~ -1) ? '$dispatch can handle "-1"' : '$dispatch cannot handle "-1"');
$dispatch .= dispatcher { match_using {$_ < 0} value => 'Less than zero' };
say (($dispatch ~~ -1) ? '$dispatch can handle "-1"' : '$dispatch cannot handle "-1"');
say $dispatch->(-1);
examples/use-syntax.pl view on Meta::CPAN
use syntax qw/maybe dispatcher/;
use Data::Dumper;
my $foo = dispatcher {
match(1);
};
print Dumper $foo;
lib/Smart/Dispatch.pm view on Meta::CPAN
package Smart::Dispatch;
use 5.010;
use strict;
use warnings;
use Carp;
use Smart::Dispatch::Table ();
use Smart::Dispatch::Match ();
BEGIN {
$Smart::Dispatch::AUTHORITY = 'cpan:TOBYINK';
$Smart::Dispatch::VERSION = '0.006';
}
use constant DEFAULT_MATCH_CLASS => (__PACKAGE__.'::Match');
use constant DEFAULT_TABLE_CLASS => (__PACKAGE__.'::Table');
our ($IN_FLIGHT, @LIST, @EXPORT);
BEGIN
{
$Carp::Internal{$_}++
foreach (__PACKAGE__, DEFAULT_MATCH_CLASS, DEFAULT_TABLE_CLASS);
$IN_FLIGHT = 0;
@LIST = ();
@EXPORT = qw/dispatcher match match_using otherwise dispatch failover/;
}
use namespace::clean ();
use Sub::Exporter -setup => {
exports => [
dispatcher => \&_build_dispatcher,
match => \&_build_match,
match_using => \&_build_match_using,
otherwise => \&_build_otherwise,
dispatch => \&_build_dispatch,
failover => \&_build_failover,
],
groups => [
default => [@EXPORT],
tiny => [qw/dispatcher match/],
],
collectors => [qw/class/],
installer => sub {
namespace::clean::->import(
-cleanee => $_[0]{into},
grep { !ref } @{ $_[1] },
);
goto \&Sub::Exporter::default_installer;
},
};
sub _build_dispatcher
{
my ($class, $name, $arg, $col) = @_;
my $table_class =
$arg->{class}
// $col->{class}{table}
// DEFAULT_TABLE_CLASS;
return sub (&)
{
my $body = shift;
local @LIST = ();
local $IN_FLIGHT = 1;
$body->();
return $table_class->new(match_list => [@LIST]);
}
}
sub _build_match
{
my ($class, $name, $arg, $col) = @_;
my $match_class =
$arg->{class}
// $col->{class}{match}
// DEFAULT_MATCH_CLASS;
return sub
{
croak "$name cannot be used outside dispatcher" unless $IN_FLIGHT;
my ($condition, %args) = (@_ == 2) ? (shift, _k($_[-1]), shift) : (@_);
push @LIST, $match_class->new(%args, test => $condition);
return;
}
}
sub _build_match_using
{
my ($class, $name, $arg, $col) = @_;
my $match_class =
$arg->{class}
// $col->{class}{match}
// DEFAULT_MATCH_CLASS;
return sub (&@)
{
croak "$name cannot be used outside dispatcher" unless $IN_FLIGHT;
my ($condition, %args) = (@_ == 2) ? (shift, _k($_[-1]), shift) : (@_);
push @LIST, $match_class->new(%args, test => $condition);
return;
}
}
sub _build_otherwise
{
my ($class, $name, $arg, $col) = @_;
my $match_class =
$arg->{class}
// $col->{class}{match}
// DEFAULT_MATCH_CLASS;
return sub
{
croak "$name cannot be used outside dispatcher" unless $IN_FLIGHT;
my (%args) = (@_ == 1) ? (_k($_[-1]), shift) : (@_);
push @LIST, $match_class->new(%args, is_unconditional => 1, test => sub {1});
return;
}
}
sub _build_dispatch
{
my ($class, $name, $arg, $col) = @_;
return sub (&)
{
croak "$name cannot be used outside dispatcher" unless $IN_FLIGHT;
return('dispatch', shift);
}
}
sub _build_failover
{
my ($class, $name, $arg, $col) = @_;
return sub (&)
{
croak "$name cannot be used outside dispatcher" unless $IN_FLIGHT;
return('dispatch', shift, is_failover => 1);
}
}
sub _k
{
ref $_[0] eq 'CODE' ? 'dispatch' : 'value';
}
foreach my $f (@EXPORT)
{
no strict 'refs';
*{"$f"} = &{"_build_$f"}(__PACKAGE__, $f, {}, {});
}
__PACKAGE__
__END__
=head1 NAME
Smart::Dispatch - first-class switch statements
=head1 SYNOPSIS
use Smart::Dispatch;
my $given = dispatcher {
match qr{ ^[A-J] }ix, dispatch { "Volume 1" };
match qr{ ^[K-Z] }ix, dispatch { "Volume 2" };
otherwise failover { Carp::croak "unexpected surname" };
};
my $surname = "Inkster";
say $surname, " is in ", $dispatch->($surname), " of the phone book.";
=head1 DESCRIPTION
People have been using dispatch tables for years. They work along the
lines of:
my $thing = get_foo_or_bar();
my %dispatch = (
foo => sub { ... },
bar => sub { ... },
);
$dispatch{$thing}->();
Dispatch tables are often more elegant than long groups of
C<if>/C<elsif>/C<else> statements, but they do have drawbacks. Consider how
you'd change the example above to deal with C<$thing> being not just "foo" or
"bar", but adding all integers to the allowed values.
Perl 5.10 introduced smart match and the C<given> block. This allows stuff
like:
my $thing = get_foo_or_bar();
given ($thing)
{
when ("foo") { ... }
when ("bar") { ... }
when (looks_like_number($_)) { ... }
}
The conditions in C<when> clauses can be arbirarily complex tests, and default
to comparisons using the smart match operator. This is far more flexible.
C<given> blocks do have some drawbacks over dispatch tables though. A dispatch
table is a first class object - you can put a reference to it in a variable,
and pass that reference as an argument to functions. You can check to see
whether a dispatch table contains particular entries:
if ($dispatch{"foo"}) # dispatch table can deal with $thing="foo"
If passed a reference to an existing dispatch table, you can easily add
entries to it, or remove entries from it.
Smart::Dispatch is an attempt to combine some of the more useful features of
C<given> with dispatch tables.
=head2 Building a Dispatch Table
All the keywords used a build a dispatch table are lexical subs, which
means that you can import them into a particular code block and they
will not be available outside that block.
=head3 C<< dispatcher { CODE } >>
A dispatch table is built using the C<dispatcher> function which takes a
single block argument. This block will typically consist of a number of
C<< match >> statements, though you can theoretically put anything you
want inside it. (The code is run just once, when the dispatch table is
being built, and is called in void context.)
my $dispatch_table = dispatcher { ... };
The return value is an L<Smart::Dispatch::Table> object.
=head3 C<< match $test, %args >>
The C<match> function adds a single entry to the current dispatch table.
The entry is a L<Smart::Dispatch::Match> object.
The C<< $test >> argument is the trigger for dispatching to that particular
entry in the table. It's like the contents of C<< when(...) >> in a
C<given> block. It is used as the right hand argument to a smart match
operation (see L<perlop>), so it can be a string/numeric constant, C<undef>,
a C<< qr/.../ >> quoted regular expression, or a coderef, or an reference
to an array containing any of the above. (There are other possibilities too,
though they are somewhat obscure.)
The hash of other arguments is passed to the constructor of
L<Smart::Dispatch::Match>.
=head3 C<< dispatch { CODE } >>
This introduces the code to run when a match has been successful. It is
used as follows:
my $dispatch_table = dispatcher {
match "foo", dispatch { "Monkey" };
match "bar", dispatch { my $x = get_simian(); return $x };
};
Actually the above is just syntactic sugar for
my $dispatch_table = dispatcher {
match "foo", 'dispatch' => sub { "Monkey" };
match "bar", 'dispatch' => sub { my $x = get_simian(); return $x };
};
So the only thing C<dispatch> is doing is depositing a coderef into the
C<%args> hash of C<match>.
=head3 C<< value => $value >>
In the case of the "Monkey" bit above, it's actually a little wasteful to
define a coderef (and run it when we do the dispatching later on) just to
return a constant string, so in this case we can use the 'value' argument
for C<match>, to provide a slight optimization:
my $dispatch_table = dispatcher {
match "foo", value => "Monkey";
match "bar", dispatch { my $x = get_simian(); return $x };
};
Note that C<value> is not a function. It's just a named argument for
C<match>. Nothing much magic is going on.
=head3 C<< match_using { CODE } %args >>
C<match_using> is exactly like C<match> but declared with a coderef
prototype (see L<perlsub>). That is, it just gives you syntactic sugar
for the case where C<$test> is a coderef. The following are equivalent:
=over
=item C<< match_using { $_ < 5 } dispatch { say "$_ is low" }; >>
=item C<< match sub { $_ < 5 }, 'dispatch' => sub { say "$_ is low" }; >>
=back
=head3 C<< otherwise %args >>
C<otherwise> is equivalent to C<default> in C<given> blocks, or C<else> in
C<if> blocks. It matches all other cases, and must thus be the last match
declared.
Again this is really just syntactic sugar. The following are equivalent:
=over
=item C<< otherwise dispatch { undef }; >>
=item C<< match sub { 1 }, 'is_unconditional' => 1, 'dispatch' => sub { undef }; >>
=back
Note that C<otherwise> explicitly marks the match as an "unconditional"
match. This allows Smart::Dispatch to complain if C<otherwise> is not the
last match in a dispatch table. And it helps when you try to combine
multiple dispatch tables to know which is the "otherwise" match.
=head3 C<< failover { CODE } >>
This is roughly the same as C<dispatch>, but is intended for marking
dispatches that can be regarded as failures:
my $roman = dispatcher {
match qr{\D}, failover { croak "non-numeric" };
match [1..3], dispatch { "I" x $_ };
match 4, value => 'IV';
match [5..8], dispatch { 'V'.('I' x ($_-5)) };
match 9, value => 'IX';
match 10, value => 'X';
otherwise failover { croak "out of range" };
};
In terms of actually dispatching from the dispatch table, failovers work
exactly the same as any other dispatches. However, because the dispatch
table knows which matches are successes and which are failures, this
information can be queried.
It should be no surprise by now that the C<failover> function is just
syntactic sugar, and the same effect can be achieved without it. The
following are equivalent:
=over
=item C<< match $test, failover {...}; >>
=item C<< match $test, 'is_failover' => 1, 'dispatch' => sub {...}; >>
=back
=head2 Using a Dispatch Table
OK, so now you know how to build a dispatch table, but once we've got
one, how can we use it?
Dispatch tables, although they are not coderefs, overload C<< &{} >>,
which means they can be called like coderefs.
my $biological_sex = dispatcher {
match 'XX', dispatch { 'Female' };
match ['XY', 'YX'], dispatch { 'Male' };
otherwise failover { '????' };
};
my $sex_chromosomes = 'XY';
say "I am a ", $biological_sex->($sex_chromosomes);
The above will say "I am a Male".
Note that the dispatch and failover subs here are pretty boring (we could
have just used C<<value>>), but any arbitrary Perl function is allowed.
Perl functions of course accept argument lists. Any argument list passed
into the dispatch table will be passed on to the dispatched function.
my $biological_sex = dispatcher {
match 'XX',
dispatch { $_[1] eq 'fr' ? 'Femelle' : 'Female' };
match ['XY', 'YX'],
dispatch { $_[1] eq 'fr' ? 'Male' : 'Male' };
otherwise
failover { '????' };
};
my $sex_chromosomes = 'XX';
say "I am a ", $biological_sex->($sex_chromosomes, 'en');
say "Je suis ", $biological_sex->($sex_chromosomes, 'fr');
Note that within C<match_using>, C<dispatch> and C<failover> blocks, the
value being matched is available in the variable C<$_>. The following
match demonstrates this:
match_using { $_ < 5 } dispatch { say "$_ is low" }
It is possible to check whether a dispatch table is able to handle a
particular value.
my $sex_chromosomes = 'AA';
if ($biological_sex ~~ $sex_chromosomes)
{
say "Dispatch table cannot handle chromosomes $sex_chromosomes";
}
else
{
say $biological_sex->($sex_chromosomes);
}
This is where C<failover> comes in. Failover matches are B<not> considered
when determining whether a dispatch table is capable of handling a value.
=head2 Manipulating Dispatch Tables
If you have an existing dispatch table, it's possible to add more entries
to it. For this purpose, Smart::Dispatch overloads the C<<< .= >>> and
C<<< += >>> operators.
my $more_sexes = dispatcher {
match 'XYY', dispatch { 'Supermale' };
match 'XXX', dispatch { 'Superfemale' };
};
$biological_sex .= $more_sexes;
The difference between the two operators is the priority is which matches
are tested.
my $match1 = dispatcher {
match 1, dispatch { 'One' };
};
We can add some more matches like this:
$match1 .= dispatcher {
match qr{^1}, dispatch { 'Leading one' };
};
When dispatching value "1", the result will still be "One", because the added
matches have lower priority than the original ones.
But if they are combined as:
$match += dispatcher {
match qr{^1}, dispatch { 'Leading one' };
};
Then when dispatching value "1", the result will be "Leading one" because
the newer matches are given higher priority.
It is also possible to use C<< . >> and C<< + >> in their non-assignment
forms:
my $enormous_match = $big_match . $large_match . $mighty_match;
(Some future version may introduce the ability to do subtraction, but there
are difficulties with this concept. For now, if you want to do subtraction,
look at the internals of Smart::Dispatch::Table.)
If one or both dispatch tables contain an unconditional match (C<otherwise>),
then these will be combined intelligently. The result will only have one
unconditional match (the higher priority one).
=head2 Import
By default Smart::Dispatch exports the following functions:
=over
=item * C<dispatch>
=item * C<dispatcher>
=item * C<failover>
=item * C<match>
=item * C<match_using>
=item * C<otherwise>
=back
It is possible to only import a subset of those:
use Smart::Dispatch qw/dispatcher match otherwise/;
As noted in the "Building a Dispatch Table" section, a minimal set of
functions is just C<dispatcher> and C<match>. All the others are
just syntactic sugar. If you just want those two, then you can do:
use Smart::Dispatch qw/:tiny/;
Smart::Dispatch uses L<Sub::Exporter> which provides a dizzying array of
cool options, such as:
use Smart::Dispatch -all => { -prefix => 'sd_' };
which imports all the symbols but prefixed with "sd_".
use Smart::Dispatch
qw/dispatcher dispatch match/,
otherwise => { -as => 'last_resort' };
which renames "otherwise" to "last_resort".
If you've written subclasses of L<Smart::Dispatch::Table> and
L<Smart::Dispatch::Match> and you want Smart::Dispatch to use your
subclasses, then you can do this:
use Smart::Dispatch
qw/dispatcher dispatch match/,
otherwise => { -as => 'last_resort' },
class => {
table => 'My::Dispatch::Table',
match => 'My::Dispatch::Match',
};
Whatsmore, the C<class> option can be set on a keyword-by-keyword basis for
C<match>, C<match_using> and C<otherwise>.
use Smart::Dispatch
qw/dispatcher dispatch match/,
otherwise => {
-as => 'last_resort',
class => 'My::Other::Match',
},
class => {
table => 'My::Dispatch::Table',
match => 'My::Dispatch::Match',
};
=head2 Constants
=over
=item * C<DEFAULT_MATCH_CLASS>
=item * C<DEFAULT_TABLE_CLASS>
=back
=head2 Dispatch Table Internals
See L<Smart::Dispatch::Table> and L<Smart::Dispatch::Match>.
Note that this is an early release, so the internals are still likely
to change somewhat between versions. The function-based API should be
fairly steady though.
=head1 BUGS
Please report any bugs to
L<http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch>.
=head1 SEE ALSO
"Switch statements" in L<perlsyn>; L<Acme::Given::Hash>.
L<http://www.perlmonks.org/?node_id=954831>.
=head1 AUTHOR
Toby Inkster E<lt>tobyink@cpan.orgE<gt>.
=head1 COPYRIGHT AND LICENCE
This software is copyright (c) 2012 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=head1 DISCLAIMER OF WARRANTIES
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
lib/Smart/Dispatch/Match.pm view on Meta::CPAN
package Smart::Dispatch::Match;
BEGIN {
*_TYPES = $ENV{PERL_SMART_DISPATCH_TYPE_CHECKS}==42
? sub () { 1 }
: sub () { 0 };
};
use 5.010;
use Moo;
use Carp;
use if _TYPES, 'MooX::Types::MooseLike::Base', ':all';
use namespace::clean;
BEGIN {
$Smart::Dispatch::Match::AUTHORITY = 'cpan:TOBYINK';
$Smart::Dispatch::Match::VERSION = '0.006';
}
use constant {
FLAG_HAS_VALUE => 2,
FLAG_HAS_DISPATCH => 4,
FLAG_IS_FAILOVER => 8,
FLAG_IS_UNCONDITIONAL => 16,
};
use overload
'&{}' => sub { my $x=shift; sub { $x->conduct_dispatch($_[0]) } },
'~~' => 'value_matches',
bool => sub { 1 },
;
has test => (
(_TYPES?(isa=>Any()):()),
is => 'ro',
required => 1,
);
has dispatch => (
(_TYPES?(isa=>CodeRef()):()),
is => 'ro',
required => 0,
predicate => 'has_dispatch',
);
has value => (
(_TYPES?(isa=>Any()):()),
is => 'ro',
required => 0,
predicate => 'has_value',
);
has note => (
(_TYPES?(isa=>Str()):()),
is => 'ro',
required => 0,
);
has bitflags => (
(_TYPES?(isa=>Num()):()),
is => 'lazy',
init_arg => undef,
);
has is_failover => (
(_TYPES?(isa=>Bool()):()),
is => 'ro',
required => 1,
default => sub { 0 },
);
has is_unconditional => (
(_TYPES?(isa=>Bool()):()),
is => 'ro',
required => 1,
default => sub { 0 },
);
sub _build_bitflags
{
my ($self) = @_;
my $rv = 1;
$rv += FLAG_HAS_VALUE if $self->has_value;
$rv += FLAG_HAS_DISPATCH if $self->has_dispatch;
$rv += FLAG_IS_FAILOVER if $self->is_failover;
$rv += FLAG_IS_UNCONDITIONAL if $self->is_unconditional;
return $rv;
}
sub value_matches
{
my ($self, $value) = @_;
local $_ = $value;
no warnings; # stupid useless warnings below
return ($value ~~ $self->test);
}
sub conduct_dispatch
{
my ($self, $value, @args) = @_;
local $_ = $value;
if ($self->has_dispatch)
{
return $self->dispatch->($value, @args);
}
elsif ($self->has_value)
{
return $self->value;
}
else
{
return;
}
}
__PACKAGE__
__END__
=head1 NAME
Smart::Dispatch::Match - an entry in a dispatch table
=head1 DESCRIPTION
Smart::Dispatch::Match is a Moose class.
(Well, L<Moo> actually, but close enough.)
=head2 Constructor
=over
=item * C<< new(%attributes) >>
Create a new entry.
=back
=head2 Attributes
=over
=item * C<test>
is 'ro', required.
=item * C<dispatch>
is 'ro', isa 'CodeRef', predicate C<has_dispatch>.
=item * C<value>
is 'ro', predicate C<has_value>.
=item * C<note>
is 'ro', isa 'Str'.
=item * C<is_failover>
is 'ro', isa 'Bool', required, default false.
=item * C<is_unconditional>
is 'ro', isa 'Bool', required, default false.
=back
=head2 Methods
=over
=item * C<< value_matches($value) >>
Perform a smart match between C<$value> and the C<test> attribute.
=item * C<< conduct_dispatch(@args) >>
If the Match object has a dispatch coderef, then calls it, passing
C<< @args >> as arguments, and passing through the return value.
Else if the Match object has a value, just returns it.
Otherwise returns nothing.
=item * C<bitflags>
Returns a number representing what sort of match this is (conditional,
failover, etc), suitable for bitwise operations with the constants
defined by this module.
=back
=head2 Constants
=over
=item * C<FLAG_HAS_VALUE>
=item * C<FLAG_HAS_DISPATCH>
=item * C<FLAG_IS_FAILOVER>
=item * C<FLAG_IS_UNCONDITIONAL>
=back
=head2 Overloads
Smart::Dispatch::Match overloads various operations. (See L<overload>.)
=over
=item * B<< code derefernce >> C<< &{} >> - C<conduct_dispatch>.
=item * B<< smart match >> C<< ~~ >> - C<value_matches>.
=back
=head1 BUGS
Please report any bugs to
L<http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch>.
=head1 SEE ALSO
L<Smart::Dispatch>.
=head1 AUTHOR
Toby Inkster E<lt>tobyink@cpan.orgE<gt>.
=head1 COPYRIGHT AND LICENCE
This software is copyright (c) 2012 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=head1 DISCLAIMER OF WARRANTIES
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
lib/Smart/Dispatch/Table.pm view on Meta::CPAN
package Smart::Dispatch::Table;
BEGIN {
*_TYPES = $ENV{PERL_SMART_DISPATCH_TYPE_CHECKS}==42
? sub () { 1 }
: sub () { 0 };
};
use 5.010;
use Moo;
use Carp;
use Scalar::Util qw/ refaddr blessed /;
use if _TYPES, 'MooX::Types::MooseLike::Base', ':all';
sub _swap
{
my ($x, $y, $swap) = @_;
$swap ? ($y, $x) : ($x, $y);
}
use namespace::clean;
BEGIN {
$Smart::Dispatch::Table::AUTHORITY = 'cpan:TOBYINK';
$Smart::Dispatch::Table::VERSION = '0.006';
}
use overload
'&{}' => sub { my $x=shift; sub { $x->action($_[0]) } },
'+' => sub { __PACKAGE__->make_combined(reverse _swap(@_)) },
'.' => sub { __PACKAGE__->make_combined(_swap(@_)) },
'+=' => 'prepend',
'.=' => 'append',
'~~' => 'exists',
'bool' => sub { 1 },
;
has match_list => (
(_TYPES?(isa=>ArrayRef()):()),
is => 'rw',
required => 1,
);
sub BUILD
{
my ($self) = @_;
$self->validate_match_list;
}
sub make_combined
{
my ($class, @all) = @_;
my $self = $class->new(match_list => []);
$self->append(@all);
}
sub validate_match_list
{
my ($self) = @_;
my @otherwise = $self->unconditional_matches;
if (scalar @otherwise > 1)
{
carp "Too many 'otherwise' matches. Only one allowed.";
}
if (@otherwise and refaddr($otherwise[0]) != refaddr($self->match_list->[-1]))
{
carp "The 'otherwise' match is not the last match.";
}
}
sub all_matches
{
my ($self) = @_;
@{ $self->match_list };
}
sub unconditional_matches
{
my ($self) = @_;
grep { $_->is_unconditional } @{ $self->match_list };
}
sub conditional_matches
{
my ($self) = @_;
grep { !$_->is_unconditional } @{ $self->match_list };
}
sub exists
{
my ($self, $value, $allow_fails) = @_;
foreach my $cond (@{ $self->match_list })
{
if ($cond->value_matches($value))
{
if ($allow_fails or not $cond->is_failover)
{
return $cond;
}
else
{
return;
}
}
}
return;
}
sub action
{
my ($self, $value, @args) = @_;
my $cond = $self->exists($value, 1);
return $cond->conduct_dispatch($value, @args) if $cond;
return;
}
sub append
{
my $self = shift;
foreach my $other (@_)
{
next unless defined $other;
carp "Cannot add non-reference to dispatch table"
unless ref $other;
carp "Cannot add non-blessed reference to dispatch table"
unless blessed $other;
if ($other->isa(__PACKAGE__))
{
$self->match_list([
$self->conditional_matches,
$other->conditional_matches,
($self->unconditional_matches ? $self->unconditional_matches : $other->unconditional_matches),
]);
}
elsif ($other->isa('Smart::Dispatch::Match')
and not $other->is_unconditional)
{
$self->match_list([
$self->conditional_matches,
$other,
$self->unconditional_matches,
]);
}
elsif ($other->isa('Smart::Dispatch::Match')
and $other->is_unconditional)
{
$self->match_list([
$self->conditional_matches,
($self->unconditional_matches ? $self->conditional_matches : $other),
]);
}
else
{
carp sprintf("Cannot add object of type '%s' to dispatch table", ref $other);
}
}
$self->validate_match_list;
return $self;
}
sub prepend
{
my $self = shift;
foreach my $other (@_)
{
next unless defined $other;
carp "Cannot add non-reference to dispatch table"
unless ref $other;
carp "Cannot add non-blessed reference to dispatch table"
unless blessed $other;
if ($other->isa(__PACKAGE__))
{
$self->match_list([
$other->conditional_matches,
$self->conditional_matches,
($other->unconditional_matches ? $other->unconditional_matches : $self->unconditional_matches),
]);
}
elsif ($other->isa('Smart::Dispatch::Match')
and not $other->is_unconditional)
{
$self->conditions([
$other,
$self->conditional_matches,
$self->unconditional_matches,
]);
}
elsif ($other->isa('Smart::Dispatch::Match')
and $other->is_unconditional)
{
$self->conditions([
$self->conditional_matches,
$other,
]);
}
else
{
carp sprintf("Cannot add object of type '%s' to dispatch table", ref $other);
}
}
$self->validate_match_list;
return $self;
}
__PACKAGE__
__END__
=head1 NAME
Smart::Dispatch::Table - a dispatch table
=head1 DESCRIPTION
Smart::Dispatch::Table is a Moose class.
(Well, L<Moo> actually, but close enough.)
=head2 Constructors
=over
=item * C<< new(%attributes) >>
Create a new dispatch table.
=item * C<< make_combined($table1, $table2, ...) >>
Combine existing tables into a new one.
=back
=head2 Attributes
=over
=item * C<match_list>
is 'rw', isa 'ArrayRef[Smart::Dispatch::Match]'.
=back
=head2 Methods
=over
=item * C<< exists($value, $include_failovers) >>
Searches for a Smart::Dispatch::Match that matches C<$value>. Ignores
failover matches, unless optional argument C<$include_failovers> is
true. Returns Smart::Dispatch::Match if it finds a match; returns nothing
otherwise.
TL;DR: checks if value C<$value> can be dispatched.
=item * C<< action($value, @additional) >>
Calls C<exists> with C<$include_failovers> set to true, then, if there
is a result, calls C<< conduct_dispatch($value, @additional) >> on that
result.
TL;DR: dispatches value C<$value>.
=item * C<conditional_matches>
Returns a list of conditional matches. (Smart::Dispatch::Match objects.)
=item * C<unconditional_matches>
Returns a list of unconditional matches. (Smart::Dispatch::Match objects.)
Should only ever be zero or one items in the list.
=item * C<all_matches>
Returns the list which is the union of the above two lists.
=item * C<< append(@things) >>
Each thing must be a Smart::Dispatch::Table or a Smart::Dispatch::Match.
Handles conflicts between unconditional matches automatically.
=item * C<< prepend(@things) >>
Each thing must be a Smart::Dispatch::Table or a Smart::Dispatch::Match.
Handles conflicts between unconditional matches automatically.
=item * C<validate_match_list>
Checks that match_list looks OK (a maximum of unconditional match;
checks that all conditional matches preceed unconditional matches).
This is done automatically after construction, prepending and
appending, but if you've manipulated the match_list manually, it's
good practice to all this method to check you've not broken it.
=back
=begin private
=item BUILD
=end private
=head2 Overloads
Smart::Dispatch::Table overloads various operations. (See L<overload>.)
=over
=item * B<< code derefernce >> C<< &{} >> - funky stuff with C<action>.
=item * B<< concatenation >> C<< . >> - funky stuff with C<make_combined>.
=item * B<< addition >> C<< + >> - funky stuff with C<make_combined>.
=item * B<< concatenation assignment >> C<< .= >> - C<append>.
=item * B<< addition assignment >> C<< += >> - C<prepend>.
=item * B<< smart match >> C<< ~~ >> - C<exists> (with C<$ignore_failover> false).
=back
=head1 BUGS
Please report any bugs to
L<http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch>.
=head1 SEE ALSO
L<Smart::Dispatch>.
=head1 AUTHOR
Toby Inkster E<lt>tobyink@cpan.orgE<gt>.
=head1 COPYRIGHT AND LICENCE
This software is copyright (c) 2012 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=head1 DISCLAIMER OF WARRANTIES
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
lib/Syntax/Feature/Dispatcher.pm view on Meta::CPAN
package Syntax::Feature::Dispatcher;
use 5.010;
use strict;
use warnings;
BEGIN {
$Syntax::Feature::Dispatcher::AUTHORITY = 'cpan:TOBYINK';
$Syntax::Feature::Dispatcher::VERSION = '0.006';
}
sub install
{
my ($class, %args) = @_;
my $into = delete $args{into};
require Smart::Dispatch;
eval "package $into; Smart::Dispatch->import;";
}
__PACKAGE__
__END__
=head1 NAME
Syntax::Feature::Dispatcher - use syntax qw/dispatcher/
=head1 DESCRIPTION
Tiny shim between L<Smart::Dispatch> and L<syntax>.
=begin private
=item install
=end private
=head1 BUGS
Please report any bugs to
L<http://rt.cpan.org/Dist/Display.html?Queue=Smart-Dispatch>.
=head1 SEE ALSO
L<Smart::Dispatch>, L<syntax>.
=head1 AUTHOR
Toby Inkster E<lt>tobyink@cpan.orgE<gt>.
=head1 COPYRIGHT AND LICENCE
This software is copyright (c) 2012 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=head1 DISCLAIMER OF WARRANTIES
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
t/01basic.t view on Meta::CPAN
use Test::More tests => 1;
BEGIN { use_ok('Smart::Dispatch') };
t/02dispatcher.t view on Meta::CPAN
use Smart::Dispatch;
use Test::More tests => 12;
use Test::Warn;
use Carp;
sub action_1_to_999 {
"1 to 999";
}
my $dispatch = dispatcher {
match 0,
value => "Zero";
match [1..10],
dispatch { "Single digit $_" };
match 1_000,
dispatch { "1e3" };
match qr/^\d{4}/,
dispatch { "Over a thousand\n"};
match_using { $_ > 0 and $_ < 1000 }
dispatch \&action_1_to_999;
otherwise
failover { Carp::carp "failover"; "F" }
};
my @x;
is scalar(@x = $dispatch->all_matches), 6, 'all_matches';
is scalar(@x = $dispatch->conditional_matches), 5, 'conditional_matches';
is scalar(@x = $dispatch->unconditional_matches), 1, 'unconditional_matches';
is $dispatch->action(0), 'Zero';
is $dispatch->action(3), 'Single digit 3';
is $dispatch->action(23), '1 to 999';
ok !$dispatch->match_list->[0]->is_failover;
ok !$dispatch->match_list->[0]->is_unconditional;
ok $dispatch->match_list->[-1]->is_failover;
ok $dispatch->match_list->[-1]->is_unconditional;
my $r;
warnings_like { $r = $dispatch->action(-1) } qr{failover}, 'failovers get run';
is $r, 'F';
t/03overloading.t view on Meta::CPAN
use Smart::Dispatch;
use Test::More tests => 5;
use Test::Warn;
use Carp;
sub action_1_to_999 {
"1 to 999";
}
my $dispatch = dispatcher {
match 0,
value => "Zero";
match [1..10],
dispatch { "Single digit $_" };
match 1_000,
dispatch { "1e3" };
match qr/^\d{4}/,
dispatch { "Over a thousand\n"};
match_using { $_ > 0 and $_ < 1000 }
dispatch \&action_1_to_999;
otherwise
failover { Carp::carp "failover"; "F" }
};
is $dispatch->(0), 'Zero';
is $dispatch->(3), 'Single digit 3';
is $dispatch->(23), '1 to 999';
my $r;
warnings_like { $r = $dispatch->(-1) } qr{failover}, 'failovers get run';
is $r, 'F';
t/04exists.t view on Meta::CPAN
use Smart::Dispatch;
use Test::More tests => 17;
use Test::Warn;
use Carp;
no warnings;
sub action_1_to_999 {
"1 to 999";
}
my $dispatch = dispatcher {
match [1..10],
dispatch { "Single digit $_" };
match 1_000,
dispatch { "1e3" };
match qr/^\d{4}/,
dispatch { "Over a thousand\n"};
match_using { $_ > 0 and $_ < 1000 }
dispatch \&action_1_to_999;
match_using { $_ < 0 }
failover { "F" }
};
ok $dispatch->exists(1);
ok !$dispatch->exists(0);
ok ($dispatch~~1);
ok !($dispatch~~0);
ok !($dispatch~~-1);
is $dispatch->(-1), 'F';
ok !($dispatch~~'Hello');
ok !defined $dispatch->('Hello');
my $match = ($dispatch ~~ 1_000);
isa_ok $match, 'Smart::Dispatch::Match', '$match';
ok $match->value_matches(1_000);
ok !$match->value_matches(999);
is $match->conduct_dispatch(1_000), '1e3';
is $match->conduct_dispatch(999), '1e3';
ok ($match ~~ 1_000);
ok !($match ~~ 999);
is $match->(1_000), '1e3';
is $match->(999), '1e3';
t/05subclassing.t view on Meta::CPAN
use Smart::Dispatch -all =>,
class => { table => 'Local::CustomDispatch::Table', match => 'Local::CustomDispatch::Match' };
use Test::More tests => 4;
use Test::Warn;
use Carp;
{
package Local::CustomDispatch::Table;
use Moo;
extends 'Smart::Dispatch::Table';
}
{
package Local::CustomDispatch::Match;
use Moo;
extends 'Smart::Dispatch::Match';
}
my $dispatch = dispatcher {
match [1..10],
dispatch { "Single digit $_" };
match 1_000,
dispatch { "1e3" };
match_using { $_ < 0 }
failover { "F" }
};
my $match = $dispatch->match_list->[0];
isa_ok $dispatch, 'Smart::Dispatch::Table', '$dispatch';
isa_ok $dispatch, 'Local::CustomDispatch::Table', '$dispatch';
isa_ok $match, 'Smart::Dispatch::Match', '$match';
isa_ok $match, 'Local::CustomDispatch::Match', '$match';