Perl - Using hashes in classes

Posted by brydgesk on Stack Overflow See other posts from Stack Overflow or by brydgesk
Published on 2010-05-26T15:08:45Z Indexed on 2010/05/26 15:11 UTC
Read the original article Hit count: 259

Filed under:

I have a class with several variables, one of which is a hash (_runs):

sub new
{
    my ($class, $name) = @_;
    my $self = {
        _name => $name,
        ...
        _runs => (),
        _times => [],
        ...
    };
    bless ($self, $class);
    return $self;
}

Now, all I'm trying to do is create an accessor/mutator, as well as another subroutine that pushes new data into the hash. But I'm having a hell of a time getting all the referencing/dereferencing/$self calls working together. I've about burned my eyes out with "Can't use string ("blah") as a HASH ref etc etc" errors.

For the accessor, what is 'best practice' for returning hashes? Which one of these options should I be using (if any)?:

return $self->{_runs};
return %{ $self->{_runs} };
return \$self->{_runs};

Further, when I'm using the hash within other subroutines in the class, what syntax do I use to copy it?

my @runs = $self->{_runs};
my @runs = %{ $self->{_runs} };
my @runs = $%{ $self->{_runs} };
my @runs = $$self->{_runs};

Same goes for iterating over the keys:

foreach my $dt (keys $self->{_runs})
foreach my $dt (keys %{ $self->{_runs} })

And how about actually adding the data?

$self->{_runs}{$dt} = $duration;
%{ $self->{_runs} }{$dt} = $duration;
$$self->{_runs}{$dt} = $duration;

You get the point. I've been reading articles about using classes, and articles about referencing and dereferencing, but I can't seem to get my brain to combine the knowledge and use both at the same time. I got my _times array working finally, but mimicking my array syntax over to hashes didn't work.

© Stack Overflow or respective owner

Related posts about perl