perl – 如何声明一个类在MooseX :: Declare中使用多个角色?

前端之家收集整理的这篇文章主要介绍了perl – 如何声明一个类在MooseX :: Declare中使用多个角色?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
鉴于角色Fooable和Barable都已定义,我怎么说FooBar类可以做Fooable和Barable?我没问题
#!/usr/bin/perl

use MooseX::Declare;

role Fooable {
    method foo { print "foo\n" }
}

role Barable {
    method bar { print "bar\n" }
}

class Foo with Fooable {}
class Bar with Barable {}

package main;

use strict;
use warnings;

Foo->new->foo;
Bar->new->bar;

但是当我尝试添加

class FooBar with Fooable,Barable {}

我得到的不是有用的错误

expected option name at [path to MooseX/Declare/Syntax/NamespaceHandling.pm] line 45

为了向自己证明我并不疯狂,我用Moose重写了它.这段代码有效(但比罪恶更丑):

#!/usr/bin/perl

package Fooable;
    use Moose::Role;    
    sub foo { print "foo\n" }

package Barable;    
    use Moose::Role;    
    sub bar { print "bar\n" }

package Foo;    
    use Moose;    
    with "Fooable";

package Bar;    
    use Moose;    
    with "Barable";

package FooBar;    
    use Moose;    
    with "Fooable","Barable";

package main;

use strict;
use warnings;

Foo->new->foo;
Bar->new->bar;
FooBar->new->foo;
FooBar->new->bar;

解决方法

显然你需要括号:
#!/usr/bin/perl

use MooseX::Declare;

role Fooable {
    method foo { print "foo\n" }
}

role Barable {
    method bar { print "bar\n" }
}

class Foo with Fooable {}
class Bar with Barable {}
class FooBar with (Fooable,Barable) {}

package main;

use strict;
use warnings;

Foo->new->foo;
Bar->new->bar;
FooBar->new->foo;
FooBar->new->bar;
原文链接:https://www.f2er.com/Perl/241670.html

猜你在找的Perl相关文章