TorontoJim has asked for the wisdom of the Perl Monks concerning the following question:
This is the first time I've tried writing a child class to a parent class. I've been googling and PerlMonk'ing for days and I'm still missing something that is obviously important.
I want to have a perl script where I call MyParent and MyParent::MyChild. Then in the code, create the object for MyParent and access the methods in MyParent::MyChild.
This is the MyParent class (MyParent.pm):
package MyParent; use strict; no strict "refs"; use Carp qw(carp croak); our $VERSION = .01; sub new { my $class = shift; bless { something => "foo", }, $class; return $self; } sub parent_nifty_method1 { print $_[0]->{something}; } sub parent_nifty_method2 { ... pah ... }
Then comes the child class MyParent::MyChild (MyChild.pm):
package MyParent::MyChild; use strict; no strict "refs"; use Carp qw(carp croak); use parent qw(MyParent); our @ISA = qw(MyParent); our @EXPORT = qw( method_a method_b ); my $VERSION = .01; sub new { my $class = shift; my $this = bless {}, $class; my( $parent ) = @_; $this->{PARENT} = $parent; return $this; } sub child_method_a { #read parent variable, not change it print MyParent->{something}; } sub child_method_b { ... incredibly cool stuff ... }
Now comes the Perl script running on the web server and what I would LIKE to do, but can't make it work, probably because I don't drink enough coffee.
script_to_change_the_world.pl #!/usr/bin/perl use MyParent; use MyParent::MyChild; use strict; my $parentobject = MyParent->new(); $parentobject->method1; #prints: Foo #Now I want to access something or other in the MyChild, doing it this + way (which is what inheritance means to me) $parentobject->child_method_a; #Prints: Foo
However, the problem is that when I do this, I get this error:
Can't locate object method "child_method_a" via package "MyParent" at +script_to_change_the_world.pl line 14.
I think I've tried to do TOO much in setting these up properly and I'm missing the variables for the methods (to use a metaphor).
Can some kind Monk please clarify what I'm doing wrong above?
Thanking you for your kindness and time.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Parent cannot call Child method
by Eily (Monsignor) on Mar 17, 2016 at 12:42 UTC | |
by TorontoJim (Beadle) on Mar 17, 2016 at 13:19 UTC | |
by jellisii2 (Hermit) on Mar 17, 2016 at 13:28 UTC | |
by TorontoJim (Beadle) on Mar 17, 2016 at 13:34 UTC | |
by Eily (Monsignor) on Mar 17, 2016 at 15:02 UTC | |
| |
|
Re: Parent cannot call Child method
by perlfan (Parson) on Mar 17, 2016 at 15:09 UTC | |
by TorontoJim (Beadle) on Mar 17, 2016 at 18:55 UTC |