What’s new?
- The BoolLike type constraint accepts boolean.pm booleans.
- Type::Params offers some improvements for DWIM named parameter processing.
- More shortcuts are provided for exporting parameterized versions of type constraints.
Improvements to Type::Params
If your function or method takes named arguments, the list_to_named
option allows these arguments to optionally be provided positionally as a shortcut:
package My::Company;
use v5.36;
use Moo;
use builtin qw( true false );
use Types::Common qw( PositiveOrZeroNum InstanceOf );
use Type::Params qw( signature_for );
...;
signature_for pay_money => (
method => true,
named => [
amount => PositiveOrZeroNum,
employee => InstanceOf['Local::Person'],
],
list_to_named => true,
);
sub pay_money ( $self, $arg ) {
$self->payroll_account->withdraw( $arg->amount );
$arg->employee->bank_account->deposit( $arg->amount );
return $self;
}
...;
my $co = My::Company->new( ... );
# Standard usage is named arguments:
$co->pay_money( amount => 3000, employee => $alice );
$co->pay_money( { amount => 3000, employee => $bob } );
# Or provide them as positional arguments in the same order
# they were declared in (amount then employee):
$co->pay_money( 3000, $carol );
# Or if the types are unambiguous, switch it up and provide
# them in the wrong order instead. Still works!
$co->pay_money( $dave, 3000 );
# Or mix and match:
$co->pay_money( $eve, amount => 3000 );
$co->pay_money( $eve, { amount => 3000 } );
$co->pay_money( 3000, employee => $eve );
$co->pay_money( 3000, { employee => $eve } );
Exporting Parameterized Types
For certain parameterizable types, there are now shortcuts to export parameterized versions of them.
For example, supposing you need to deal with numeric arrayrefs quite a lot. That is, arrayrefs containing only numbers. Previously, you’d probably do something like this:
use Types::Common qw( Num ArrayRef );
...;
has favourite_numbers => ( is => 'ro', isa => ArrayRef[Num] );
...;
if ( ArrayRef->of( Num )->check( \@my_array ) ) {
...;
}
Now you can easily create a Nums type constraint and use it:
use Types::Common qw( Num );
use Types::Standard::ArrayRef Nums => { of => Num };
...;
has favourite_numbers => ( is => 'ro', isa => Nums );
...;
if ( is_Nums \@my_array ) {
...;
}
Not all parameterizable types support this, but many of the common ones do.
Top comments (0)