我在这个网站上的第一个问题,我很快就来了。我是一名开发人员,主要使用Python和Perl。我充满激情,我非常喜欢开发。
我的第一个问题是关于Perl,Moo和Type::Tiny的。类型:: Tiny当然是与Moo一起使用的一个很棒的模块,但是我将在另一个问题中回到这个主题。
我发现Types::Path::Tiny是Moose和Moo的模块强制,因此我尝试在类中创建一个属性目录,如documentation所述,因为我的项目在Moose中有效,但是由于我在Moo中移动,它不再起作用:
package MahewinBlogEngine::Common;
use strict;
use warnings;
use feature "state";
use Moo;
use Types::Path::Tiny qw/Path AbsPath/;
use CHI;
use MahewinBlogEngine::Renderer;
use Type::Params qw( compile );
use Types::Standard qw( slurpy Object Str HashRef ArrayRef );
=attr directory
rw, required, Str. The directory contain articles.
=cut
has 'directory' => (
is => 'rw',
isa => AbsPath,
required => 1,
coerce => 1,
);
在我的测试目录中:
my $articles = MahewinBlogEngine->articles( directory => getcwd() . '/t/articles' );
错误是:
Invalid coerce '1' for MahewinBlogEngine::Common->directory not a coderef or code-convertible object at /home/hobbestigrou/perl5/perlbrew/perls/perl-5.19.1/lib/site_perl/5.19.1/Method/Generate/Accessor.pm line 618.
Compilation failed in require at /home/hobbestigrou/perl5/perlbrew/perls/perl-5.19.1/lib/site_perl/5.19.1/Module/Runtime.pm line 317.
Compilation failed in require at /home/hobbestigrou/MahewinBlogEngine/lib/MahewinBlogEngine.pm line 8.
BEGIN failed--compilation aborted at /home/hobbestigrou/MahewinBlogEngine/lib/MahewinBlogEngine.pm line 8.
Compilation failed in require at ./benchmark.pl line 10.
BEGIN failed--compilation aborted at ./benchmark.pl line 10.
这是正常现象,因为在Moo中,强制是一个coderef,因此我尝试了:
has 'directory' => (
is => 'rw',
isa => AbsPath,
required => 1,
coerce => sub { return "Path" }
);
错误是:
value "Path" did not pass type constraint "Path" (not isa Path::Tiny) (in $self->{"directory"}) at (eval 355) line 99.
如果我没有胁迫:
value "/home/hobbestigrou/MahewinBlogEngine/t/articles" did not pass type constraint "Path" (not isa Path::Tiny) (in $self->{"directory"}) at (eval 355) line 89.
对于这个简单的问题,我感到很抱歉,我一定很愚蠢,并且错过了一些东西,但是我看不到文档中可能缺少的东西。
谢谢
最佳答案
如果您拥有use strict;
,则没有理由拥有use warnings;
和use Moo;
,因为它可以为您做到这一点。
您还必须给Moo一个coerce
元素的代码引用,而不是真实值。
使用Type::Tiny可以通过调用$type->coercion
来实现。
package MahewinBlogEngine::Common;
# not needed with Moo
# use strict;
# use warnings;
use Moo;
use Types::Path::Tiny qw/AbsPath/;
...
has 'directory' => (
is => 'rw',
isa => AbsPath,
required => 1,
coerce => AbsPath->coercion,
);
for( qw'/home ./ ./Documents Documents' ){
use feature 'say';
say $_, "\t", MahewinBlogEngine::Common->new( directory => $_ )->directory;
}
/home /home
./ /home/user
./Documents /home/user/Documents
Documents /home/user/Documents
关于perl - 如何在Moo中使用Types::Path::Tiny,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18243304/