in reply to displaying package variable from inherited method.

This:
print $proto::data
Prints the variable $data in package "proto". Not the variable $data in package $proto, so to speak.

To fix this, you'll need a symbolic reference. Like

no strict 'refs'; print ${"${proto}::data"};
I don't really like this setup, though. Personally I'd prefer using closures to access the data.

Replies are listed 'Best First'.
Re^2: displaying package variable from inherited method.
by wazoox (Prior) on Jun 10, 2006 at 15:00 UTC
    ...Prints the variable $data in package "proto".

    Bummer... Of course ! shame on me... So there isn't any way around ? What do you think of this :

    Child.pm :
    use strict; use warnings; package Child; use Data::Dumper ; use base 'Parent' ; sub data { return { one => 1, two => 2 } }; 1;
    Then Parent.pm:
    use strict; use warnings; package Parent; use Data::Dumper ; sub new { my $proto = shift ; return bless {}, $proto } sub show { my $self = shift ; my $proto = ref $self ; print $proto->data(); print Dumper $proto->data() } 1;

    The script code remains of course unchanged. Unless I... May it be possible to get it working the way I meant by using tie ?

      In that example you're not actually sharing the data: you're creating a new hash every time data() is called. If you really want to share the data, you can do:

      my $data = { one => 1, two => 2 }; sub data { return $data; }

      I don't know how you'd use tie() to get the original code to work. If you really want that construct, you'll need to use symbolic references or - even more dangerous - eval.

      Also note that even if it would work as you expected, the original code will break as soon as someone subclasses Child.

      update: in the example you posted here, there's no need to do

      my $proto = ref $self; print $proto->data;
      You can just call
      print $self->data;
        In that example you're not actually sharing the data: you're creating a new hash every time data() is called.

        How unfortunate I am ! I can't have all my bad code reviewed by your sharp eyes, precious friend. Thanks a lot for this one :)

        update: in the example you posted here, there's no need to do
        my $proto = ref $self;
        print $proto->data;

        Yes, this one is just a hurried copy-and-paste :)