Is it possible to get existing moose objects, and not create new ones when the same required attributes are provided?

Suppose I have the following Moose package:

package GSM::Cell;
use Moose;

has 'ID' => (is => 'ro', required => 1);
has [qw(BCCH NEIGHBOUR)] => (is => 'rw', default => undef);

no Moose;
__PACKAGE__->meta->make_immutable; 
1;

Then I create two objects and add them as the NEIGHBOR attribute of the other:

my $a = GSM::Cell->new(ID => 20021, BCCH => 1);
my $b = GSM::Cell->new(ID => 20022, BCCH => 2);
$a->NEIGHBOUR($b);

Somewhere else, for example. in another procedure, the attribute BCCH $ b can be updated to a different value:

$b->BCCH(3);

Now if i turn to

 $a->NEIGHBOUR->BCCH

then I will still return my initial value for the BCCH attribute instead of the updated value.

I think the smart thing is to add a link to $ b instead of $ b itself, which would solve the problem:

$a->NEIGHBOUR(\$b);

, -, , $b ( ), , , .

,

my $somevar = GSM::Cell->new(ID => 20022);

, .

, - :

$id = 20022;
my $somevar = $already_created{$id} || GSM::Cell->new(ID => $id);

?

+3
3

- MooseX::NaturalKey .

package GSM::Cell;
use MooseX::NaturalKey;

has 'ID' => (is => 'ro', required => 1);
has [qw(BCCH NEIGHBOUR)] => (is => 'rw', default => undef);

primary_key => ('ID');
no Moose;
__PACKAGE__->meta->make_immutable; 
1;

:

my $a = GSM::Cell->new(ID => 20021, BCCH => 1);
my $b = GSM::Cell->new(ID => 20022, BCCH => 2);
$a->NEIGHBOUR($b);
$b->BCCH(3);
say $a->NEIGHBOR->BCCH; # prints 3

my $c = GSM::Cell->new(ID => 20022);
$c->BCCH(4);
say $a->NEIGHBOR->BCCH; # prints 4
+3
  • , 20021 20022? BCC -, .

  • , , $Network factory, , $Network ...

+2

, , , .

:

package GSM::Cell;
use Moose;

has 'ID' => (is => 'ro', required => 1);
has [qw(BCCH NEIGHBOUR)] => (is => 'rw', default => undef);

no Moose;
__PACKAGE__->meta->make_immutable; 
1;

package main;

my $a = GSM::Cell->new(ID => 20021, BCCH => 1);
my $b = GSM::Cell->new(ID => 20022, BCCH => 2);
$a->NEIGHBOUR($b);

$b->BCCH(3);
print $a->NEIGHBOUR->BCCH, "\n";  # 3

It prints the updated value, not the old value. It works because it $bis an object, and all Perl objects are blissful references. When you start $a->NEIGHBOUR($b), you are already passing the link; no need to transfer link to link.

+1
source

Source: https://habr.com/ru/post/1724073/


All Articles