Re: Data inheritance
by ikegami (Patriarch) on Sep 23, 2011 at 18:17 UTC
|
package Base;
use strict;
use warnings;
sub new {
my $class = shift;
return bless({}, $class);
}
1;
package Child;
use strict;
use warnings;
use Base;
our @ISA = qw( Base );
sub new {
my $class = shift;
my $self = $class->SUPER::new();
$self->{nums} = [qw( 1 2 )];
return $self;
}
1;
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
So this code isnt working..
CommonObject.pm
my $some_var;
#constructor
sub new{
my $class=shift;
my $self = {} ;
bless $self, $class;
print Dumper($self);
return $self;
}
MyObject.pm
our @ISA = qw( CommonObject );
sub new{
my $class=shift;
$testName=shift;
my $self = CommonObject->new();
$self->some_var="abcd";
return $self;
}
I want to be able to set some_var here.
I get error Global symbol "$some_var" requires explicit package name. Isnt inheritance supposed to get the variable into MyObject??
| [reply] [Watch: Dir/Any] [d/l] |
|
| [reply] [Watch: Dir/Any] [d/l] |
|
|
|
|
|
|
Re: Data inheritance
by ikegami (Patriarch) on Sep 23, 2011 at 18:26 UTC
|
...Then again, I see that you actually have my @common_array;. If that's what you want to set, ignore objects and classes. That variable has nothing to do with either.
If all the code is in the same file, you can simply do @common_array = qw(1 2); since you are still in the same lexical scope.
If the definition (my @common_array;) and the code from which you want to access @common_array are in separate files, then you can't access the array from that code since the array is outside of the scope of the code in question.
You could work around that problem by using a package variable (our @common_array;) instead of a lexical variable (my @common_array;). Package variables are globally scoped (if you use their full name), which means you can access the array as @CommonObject::common_array from anywhere.
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
Hi ikegami,
Thank you for yor replies. The packages are not in the same file. CommonObject is meant to be used by multiple child class objects. I just put all the common variables in the CommonObject.
So the question is, which is better:
Make the array variable a ref variable and do
$self->$common_array_ref=1,1;
or
make it package scope variable.
| [reply] [Watch: Dir/Any] |
|
Between the two options you gave, I would go with the one that compiles.
Of course, it's not between the two options you gave. What's with using global variables, especially one that gets clobbered every time you create an object.
| [reply] [Watch: Dir/Any] |
|
|
Re: Data inheritance
by SuicideJunkie (Vicar) on Sep 23, 2011 at 18:21 UTC
|
my $self = {}; # is a hash ref
$self->{foo}; # element foo of that hash
$self->{foo} = ['bar', 'baz']; # assign an arrayref to that element
@{$self->{foo}}; # element of the hash, dereferenced as
+an array.
@{$self->{foo}} = (1,2); # assign (1, 2) to the array.
push @{$self->{foo}}, (3); # array now contains 1,2,3
| [reply] [Watch: Dir/Any] [d/l] |