slower has asked for the wisdom of the Perl Monks concerning the following question:
I seek your wisdom in determining the best way to access a package variable of a subclass from within a base class method. I have identified a working solution, but it is ugly and I don't completely understand it. It also uses stringy eval, which I know to be taboo in most cases.
Surely there must be a more elegant (or correct) way for a method in a base class to access the package variables of the subclass that inherited it?
Thanks in advance, and here is some functional example code illustrating what I am trying to accomplish.
m.
#================= package BaseClass; #================= our $ID = 1; sub new { my $class = shift; return bless {}, $class; } sub id { my $self = shift; my $class = ref $self; return eval "\$${class}::ID"; } #================ package SubClass; #================ use base qw( BaseClass ); our $ID = 2; #============ package main; #============ my $obj = new SubClass; my $id = $obj->id(); print "$id\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Access package variables of subclass from base class
by moritz (Cardinal) on Mar 04, 2009 at 08:24 UTC | |
by slower (Acolyte) on Mar 05, 2009 at 16:18 UTC | |
|
Re: Access package variables of subclass from base class
by GrandFather (Saint) on Mar 04, 2009 at 08:49 UTC | |
by Anonymous Monk on Mar 04, 2009 at 12:36 UTC | |
|
Re: Access package variables of subclass from base class
by targetsmart (Curate) on Mar 04, 2009 at 08:32 UTC | |
by slower (Acolyte) on Mar 04, 2009 at 16:56 UTC | |
|
Re: Access package variables of subclass from base class
by ig (Vicar) on Mar 04, 2009 at 08:50 UTC |