Why doesn't the following code, ripped directly from the docs, work?
package Types::Mine {
use Scalar::Util qw(looks_like_number);
use Type::Library -base;
use Type::Tiny;
my $NUM = "Type::Tiny"->new(
name => "Number",
constraint => sub { looks_like_number($_) },
message => sub { "$_ ain't a number" },
);
__PACKAGE__->meta->add_type($NUM);
__PACKAGE__->meta->make_immutable;
}
When I try to ->import it from the same file.
package main {
use v5.30;
BEGIN { Types::Mine->import( qw(Number) ) };
die Number;
}
I'm getting,
Could not find sub 'Number' exported by Types::Mine at /tmp/test.pl line 20.
BEGIN failed--compilation aborted at /tmp/test.pl line 20.
Shouldn't you be able to import a type library declared in the same file, though a different package, with
BEGIN { Types::Mine->import( qw(Number) ) };
You have to either
Wrap the
packageinBEGIN {}, because remember if you're trying to writeusein one package, therequireand theimportis in theBEGIN {}block too, ie these two are the sameSo you'll want to wrap the entire package in the
BEGIN {}block, AND theimportstatement,Cheat, and put nothing in
BEGIN, but predeclare the sub.Note this method generates a warning for "Overwriting existing sub" in
Exporter::Tiny, which can be silenced by instead doing,First option provided by
ilmari.