在Perl/Moose中,我可以使用两个具有相互依赖的默认值的属性吗?

Rya*_*son 5 perl attributes moose

我可以在穆斯这样做吗?

package SomeClass;
use Moose;

has start => (
    isa => 'Int',
    is => 'ro',
    lazy => 1,
    default => sub { $_[0]->end },
);

has end => (
    isa => 'Int',
    is => 'ro',
    lazy => 1,
    default => sub { $_[0]->start },
);

...
Run Code Online (Sandbox Code Playgroud)

换句话说,我想要两个名为"start"和"end"的属性,如果只指定了其中一个属性,我希望将另一个属性设置为相同的东西.不指定任何一个是错误.

这种相互依赖的设置是否有效?

Eth*_*her 17

是的,如果通过验证至少指定了其中一个值来删除无限递归的可能性:

has start => (
    ...
    predicate => 'has_start',
);

has end => (
    ...
    predicate => 'has_end',
);

sub BUILD
{
    my $self = shift;

    die "Need to specify at least one of 'start', 'end'!" if not $self->has_start and not $self->has_end;
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以将检查延迟到默认子设备:

has start => (
    ...
    predicate => 'has_start',
    default => sub {
        my $self = shift;
        die "Need to specify at least one of 'start', 'end'!" if not $self->has_end;
        $self->end;
    },
);

has end => (
    ...
    predicate => 'has_end',
    default => sub {
        my $self = shift;
        die "Need to specify at least one of 'start', 'end'!" if not $self->has_start;
        $self->start;
    },
);
Run Code Online (Sandbox Code Playgroud)