in reply to Moo's coerce and isa difference
Because of the dynamic nature of perl, it isn't possible to eliminate isa checks in a general way. It is certainly possible to do in your own code though. For example:
package MyApp::SomeObject; use constant DEBUG => $ENV{MYAPP_DEBUG}; use Moo; has foo => ( is => 'ro', ( DEBUG ? ( isa => sub { my $value = shift; if ($value !~ /^[0-9]+$/) { die "Not an integer: $value"; } } ) : () ), );
Note that isa and coerce work slightly differently in Moose vs Moo. In Moose, first it performs the isa check. If that fails, it tries to do a coercion. The result of the coercion is then validated with the isa check. These checks are tied to Moose's type system.
Moo doesn't have a type system, so its isa and coerce are both just coderefs. The coerce sub is always run (if it exists), then its result is checked with the isa sub (if it exists). The isa sub should throw an exception on invalid values. Its return value is ignored. The coerce sub should return the coerced value. It would be possible to do all of this logic in a coerce sub, but it is convenient to be able to specify them separately.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Moo's coerce and isa difference
by krautcat (Acolyte) on Sep 14, 2017 at 18:46 UTC | |
by 1nickt (Canon) on Sep 15, 2017 at 17:52 UTC |