Thenothing has asked for the wisdom of the Perl Monks concerning the following question:
Hi everyone I hope you're doing fine, first I want to say this is crosspost: https://stackoverflow.com/questions/77557869/central-constructor-share-data-bless-hash-between-packages
I will tried to explain better here and find a solution to this problem, and I hope to learn something new.
I want to have access the latest data of parent constructor in all childs packages in $self.
why I want to do this:
In the constructor, I call external packages so I assigned the result to the hash reference constructor, inside child package I need that data and others config values of parent.
Possible solution:
I found a solution with rebless, and with this code, but I need to create variable and I have to call $self->{data}->{key} I want to avoid that . I wish I can call just like this $self->{key} inside child package without rebless.
Here a full working example, but have to call $self->{data}->{key}:
do you have some suggestions ?package Father; my $store_data = { }; sub new { my $class = shift; return bless { data => $store_data }, $class; } 1; package Daughter; use parent qw(Father); sub status { my $self = shift; $self->{data}->{news} = 'bad'; return $self; } sub other { my $self = shift; return $self; } 1; package Son; use parent qw(Father); sub set { my $self = shift; $self->{data}->{news} = 'good'; return $self; } 1; use Daughter; use Son; my $self = Daughter->new()->status; print Dumper($self); $self = Son->new()->set; print Dumper($self); $self = Daughter->new()->other; print Dumper($self); $VAR1 = bless( { 'data' => { 'news' => 'bad' } }, 'Daughter' ); $VAR1 = bless( { 'data' => { 'news' => 'good' } }, 'Son' ); $VAR1 = bless( { 'data' => { 'news' => 'good' } }, 'Daughter' );
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Share data bless hash of parent package with childs packages
by 1nickt (Canon) on Dec 17, 2023 at 14:29 UTC | |
by Corion (Patriarch) on Dec 17, 2023 at 16:06 UTC | |
|
Re: Share data bless hash of parent package with childs packages
by Anonymous Monk on Dec 19, 2023 at 11:28 UTC | |
by bliako (Abbot) on Dec 19, 2023 at 11:32 UTC | |
by soonix (Chancellor) on Dec 19, 2023 at 11:59 UTC | |
by bliako (Abbot) on Dec 19, 2023 at 12:08 UTC |