आप आलसी आरंभीकरण के साथ खेल खेलने सकता है:
BEGIN {
for (qw/ parent child /) {
no strict 'refs';
my $squirreled = "_" . $_;
*{"_build" . $squirreled} = sub {
my($self) = @_;
my $proto = $self->$squirreled;
ref $proto eq "REF" ? $$proto : $proto;
};
*{"has" . $squirreled} = sub {
my($self) = @_;
defined $self->$squirreled;
};
}
}
यह
my $a = Node->new(parent => \my $b, name => "A");
$b = Node->new(child => $a, name => "B");
for ($a, $b) {
print $_->name, ":\n";
if ($_->has_parent) {
print " - parent: ", $_->parent->name, "\n";
}
elsif ($_->has_child) {
print " - child: ", $_->child->name, "\n";
}
}
इसका उत्पादन होता है की अनुमति देता है:
package Node;
use Moose;
has parent => (
is => 'ro',
isa => 'Node',
lazy => 1,
init_arg => undef,
builder => '_build_parent',
);
has _parent => (
is => 'ro',
init_arg => 'parent',
);
has child => (
is => 'ro',
isa => 'Node',
lazy => 1,
init_arg => undef,
builder => '_build_child',
);
has _child => (
is => 'ro',
init_arg => 'child',
predicate => undef,
);
has name => is => 'ro', isa => 'Str';
बिल्डरों और मक्खी पर विधेय उत्पन्न
A:
- parent: B
B:
- child: A
कोड η-conversion के साथ और अधिक सुंदर हो सकता है, लेकिन मूस बिल्डर तरीकों के पैरामीटर पास नहीं होंगे।
शायद एक बेवकूफ सवाल है, लेकिन अपरिवर्तनीयता क्यों मायने रखती है? – Ether
मेरे लिए यह 'नोड' ऑब्जेक्ट्स के बारे में कारण बनाना आसान बनाता है। अन्य कारणों से 'अपरिवर्तनीयता' टैग देखें। – zoul