NAME

match::simple::sugar - a few extras for match::simple

SYNOPSIS

This module provides a given/when substitute for match::simple.

use match::simple::sugar;

for ( $var ) {
   when 'foo',        then { ... };
   when 'bar', 'baz', then { ... };
   ...;  # otherwise
}

It also provides a function for numeric matching (because match::simple always assumes you want stringy matching if the right-hand-side is a defined non-reference value).

use match::simple::sugar;

for ( $var ) {
   when numeric 0, then { ... };
   when numeric 1, then { ... };
   ...;  # otherwise
}

DESCRIPTION

This module exports three functions when, then, and numeric, and also re-exports match from match::simple.

when and then

The when and then functions are intended to be used together, inside a for ( SCALAR ) { ... } block. The block acts as a topicalizer (it sets $_) and also a control-flow mechanism (when can use next to jump out of it). Any other use of when and then is unsupported.

when( @values, $then )

The when function accepts a list of values, followed by a special $then argument.

If $_ matches (according to the definition in match::simple) any of the values, then the $then argument will be executed, and when will use the Perl built-in next keyword to jump out of the surrounding for block.

then { ... }

The then function takes a block of code and returns an object suitable for use as when's $then argument.

In the current implementation, the block of code should not inspect @_ or wantarray, and should not use the return, next, last, or redo keywords. (If you set any of the PERL_STRICT, EXTENDED_TESTING, AUTHOR_TESTING, or RELEASE_TESTING environment variables to true, then match::simple::sugar will try to enforce this! This is intended to catch faulty then blocks when running your test suite.)

numeric

The numeric function accepts a number and returns a blessed object which has a MATCH method. The MATCH method returns true if it is called with a single defined non-referece scalar that is numerically equal to the original number passed to numeric. Example:

numeric( '5.0' )->MATCH( '5.000' );    # true

This is intended for use in cases like:

if ( match $var, numeric 1 ) {
   ...;
}

BUGS

Please report any bugs to https://github.com/tobyink/p5-match-simple/issues.

SEE ALSO

match::simple.

This module uses Exporter::Tiny.

AUTHOR

Toby Inkster <tobyink@cpan.org>.

This module is inspired by a talk I gave to Boston.PM.

COPYRIGHT AND LICENCE

This software is copyright (c) 2023 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.