%fields was defined as a lexical
my variable, so you cannot access it from the symbol table (ie,
%{"${class}::fields"}). Define the hash as an
our global variable (or
use vars qw/%fields/; globals) in both classes and you can do it. This uses a taste of polymorphism (not really true polymorphism) in the
new constructor -- no matter what inherited class it was called from, it uses that class's
%fields hash.
If you don't like bodging in the symbol table (won't work under strict), it might be smoother would be to have a fields accessor sub in each class that would simply return the %fields hash:
package SomePackage;
my %fields = ( name => undef ); ## can be a lexical
### here's a new simple accessor
sub fields { return %fields };
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my %args = @_;
### added this line
my %fields = $class->fields;
my $self = {
_permitted => \%fields,
%fields,
};
bless($self, $class);
foreach my $arg (keys(%args)) {
$self->$arg($args{$arg});
}
}
## ... elsewhere
package Some::Package::Sub;
use base 'Some::Package'; ### you needed this line before
my %fields = ( name => undef, required => undef );
sub fields { return %fields };
This uses true polymorphism by calling
$class->fields. You can keep the
%fields hash as a lexical within the classes as well.
blokhead
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.