kernelsanders has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I'm having trouble accessing child data from a base class method. Instead of a reference to the class data, I'm getting a reference to an empty array. Can anyone tell me what I'm doing wrong?

BaseClass.pm:

package BaseClass; sub _classobj { my $invocant = shift; my $class = ref $invocant || $invocant; no strict "refs"; return \%$class; } sub new { my $invocant = shift; my $class = ref $invocant || $invocant; my $classData = $class->_classobj(); my $name = $classData->{Column_Header}; my $value = (@_) ? shift : undef; bless { name => "$name", value => "$value", cdata => \%classData, }, $class; } sub get_column { my $invocant = shift; my $class = ref ($invocant) || $invocant; my $cdata = $class->_classobj; unless defined "$cdata" { print "class data not found \n"; die; } my $column = $$cdata->{Input_column}; return $column; } 1;

ChildClass.pm
package ChildClass; use base qw(BaseClass); our %ChildClass = ( Blank_ok => 'no', Column_header=> '^(cell|name)$', Field_length => 20, Input_column => 'Unknown', Invalid_characters => '[^\W-]', ); 1;
test_script.pl
#! /usr/bin/perl use strict; use warnings; use diagnostics; use Carp; use ChildClass; print "column: ", ChildClass->get_column;

I tried to mimick the setup listed here perltootc. When at the return statement for _classobj() in the debugger I get the following for each command:

> p $class<br> ChildClass<br> > x %ChildClass<br> empty array<br> > x %ChildClass::ChildClass<br> 0 'Invalid_characters'<br> 1 '[^\\W-]'<br> 2 'Column_header'<br> 3 '^(cell|name)$'<br> 4 'Blank_ok'<br> 5 'no'<br> 6 'Input_column'<br> 7 'Unknown'<br> 8 'Field_length'<br> 9 20
Why should I have to fully qualify the ChildClass hash? In the perltootc tutorial that doesn't seem to be necessary from the _classobj method...

Replies are listed 'Best First'.
Re: Trouble Accessing Class Data
by lamprecht (Friar) on Oct 15, 2009 at 22:55 UTC

    you are accessing %BaseClass::ChildClass in _classobj() where you want %ChildClass::ChildClass which holds your class data.

    There are more errors which you can easily find by using strict and warnings in your modules as well. Also  use Moose; Moose will make your OO - exercises more fun.


    Cheers, Christoph

    update: added link