Front page | perl.beginners |
Postings from October 2011
Re: Hash in a class
Thread Previous
|
Thread Next
From:
John SJ Anderson
Date:
October 28, 2011 04:23
Subject:
Re: Hash in a class
Message ID:
0D20965669AC4EFBA6CDA1686C2631B6@genehack.org
On Friday, October 28, 2011 at 07:05 , Gary wrote:
> sub new {
> my ($class, $file_name) = @_;
> my $self = {
> _file_name => $file_name,
>
> _cfg => {} # <--<< the hash i want to access
> };
> bless $self, $class;
> return $self;
> }
>
> but I can't work out how to access self->_cfg and its elements.
>
What you get back from calling this 'new' method is just a hash ref -- it's a jumped-up hash ref that knows it belongs to a particular class, but underneath, it's still ultimately just a hash ref, so you use the standard 'dereference with the bracket type appropriate for the underlying variable type' syntax, i.e., curlies.
my $thing = CLASS->new();
$thing->{_cfg}{key} = 'value';
There are more elaborate ways to do this, and an argument to be made that directly accessing stuff like this violates your object encapsulation. I'm pretty sure somebody else will spell those out in more detail sooner or later. 8^)
chrs,
john.
Thread Previous
|
Thread Next