in reply to object oriented Perl advice / constructor creation in child class
G'day smarthacker67,
While I assume you're just using "A", "B", etc. as examples, this generally isn't a good idea as you can run into name collisions; for instance, B.pm is a core module which you'll already have installed.
I don't understand where "C1.pm" sits in your hierarchy. It seems to be both a file and directory which is a subdirectory of another file ("C.pm"). Obviously that can't be the case but I don't know what you want: "lib/C/C1.pm"?, "lib/C1.pm"?, something else?
Here's some skeleton code to show how you might achieve this sort of thing with Moose. This is intended as an academic exercise: there's no suggestion that this is production-grade code; nor that Moose is the best choice for your specific application.
$ cat lib/A.pm package A; use Moose; has bar => ( is => 'rw', default => 'A-bar', ); __PACKAGE__->meta->make_immutable;
$ cat lib/C.pm package C; use Moose; sub whos_who { my ($self) = @_; print "whos_who() is in package: ", __PACKAGE__, "\n"; print "\$self is in package: ", ref($self), "\n"; return; } __PACKAGE__->meta->make_immutable;
$ cat lib/D.pm package D; use Moose; has 'bar' => ( is => 'rw', default => 'D-bar', ); __PACKAGE__->meta->make_immutable;
$ cat lib/C1.pm package C1; use Moose; extends 'C'; use A; use D; has a => ( is => 'ro', default => sub { A->new } ); has d => ( is => 'ro', default => sub { D->new } ); sub foo { my ($self) = @_; print $self->a, "\n"; print $self->a->bar, "\n"; print $self->d, "\n"; print $self->d->bar, "\n"; $self->whos_who; return; } __PACKAGE__->meta->make_immutable;
$ cat ./acd.pl #!/usr/bin/env perl use strict; use warnings; use lib 'lib'; use C1; my $c1 = C1::->new(); $c1->foo();
$ ./acd.pl A=HASH(0x25db7c0) A-bar D=HASH(0x25db880) D-bar whos_who() is in package: C $self is in package: C1
Update (typo fix): s{lib/C/C.pm}{lib/C/C1.pm}
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: object oriented Perl advice / constructor creation in child class
by smarthacker67 (Beadle) on Jul 11, 2018 at 06:45 UTC | |
by kcott (Archbishop) on Jul 11, 2018 at 07:15 UTC |