Skip to content

Old School OO Perl with arrays and hashes

Sometimes when I write OO Perl code I get confused on how to use Array and Hash as Class attribute.

This is a code sample showing how to create a Class with `Array` and `Hash`. The following Class has three attributes ‘userid’, ‘array_ref’, and ‘hash_ref’:

sub new {
    my ($class, $args) = @_;
    my $self = {
        userid => 12345,
        array_ref => [], # Array
        hash_ref => {}, # Hash
    };
    return bless $self, $class;
}

To push any data into ‘array_ref’, we need to reference/dereferencing to its array `@{ $self->{array_ref} }`.

sub add_list {
    my ($self, $id) = @_;
    push @{ $self->{array_ref} }, $id;
}

To print `array_ref` content, we also need to reference/dereferencing.

sub list_mylist {
    my $self = shift;
    for my $I (@{ $self->{array_ref} }) { say $I; }
}

For hashes, there are two different ways to do the same task. The problem is: I have no idea which one is the fastest.

sub add_hash {
    my ($self, $id) = @_;
    #$self->{hash_ref} = {foo=> $id};  #works
    $self->{hash_ref}->{foo} = $id; # works
}

To print `hash_ref` content we also need to make a reference/dereferencing:

sub list_hash {
    my $self = shift;
    for my $k ( keys %{ $self->{hash_ref} } ) {
        say "key: ", $k, " value ", $self->{hash_ref}{$k};
    }
}

Here is the complete code:

package myclass;
use strict;
use warnings;
use feature qw/say/;

sub new {
    my ($class, $args) = @_;
    my $self = {
        userid => 12345,
        array_ref => [],
        hash_ref => {},
    };
    return bless $self, $class;
}
sub add_list {
    my ($self, $id) = @_;
    push @{ $self->{array_ref} }, $id;
}
sub list_mylist {
    my $self = shift;
    for my $I (@{ $self->{array_ref} }) { say $I; }
}
sub add_hash {
    my ($self, $id) = @_;
    #$self->{hash_ref} = {foo=> $id};
    $self->{hash_ref}->{foo} = $id;
}
sub list_hash {
    my $self = shift;
    for my $k ( keys %{ $self->{hash_ref} } ) {
        say "key: ", $k, " value ", $self->{hash_ref}{$k};
    }
}

1;

my $foo = myclass->new();
$foo->add_list(123);
$foo->add_list(124);
$foo->list_mylist();
$foo->add_hash(12345);
$foo->list_hash();

References:

http://stackoverflow.com/questions/24725370/error-using-keys-on-a-hash
http://perltricks.com/article/25/2013/5/20/Old-School-Object-Oriented-Perl/

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.