Plexus Plexus - 1 month ago 7
Perl Question

A class contains a hash object, I want to call a function to populate the hash values by key

I made the class as follows:

package Tool;

sub new {

my ( $class, %args ) = @ARG;

my $self = bless {
#hash reference
_ToolParameters => { }

}, $class;

return $self;

}


I then want to create an instance of this class:

my $Object = Tool->new();


then, I'd like to read from a textfile to populate the hash:

$Object->ImportData;


in this function ImportData, I would like to use an ID as a key,
then populate a number of fields, where the long and short of it is the function comes to a point where I need to populate the hash using the key as follows:

foreach my $entry (@rows)
{

my $key = $entry->[0];
my $parameter = $entry->[1];
my $parameter2 = $entry->[2];

push @{$self->{key}}, $key;
#now to this key, I'd like to attach these 2 parameters, and values for these parameters
}


Basically when I return from this list I'll have something like:

key1 -> parameter1 = 0
-> parameter2 = 0

key2 -> parameter1 = 0
-> parameter2 = 1


as defined by the input file

Ideas anyone? Thank you.

Answer

It's unclear what you want.

To produce

{
    key1 => {
        parameter1 => 0,
        parameter2 => 0,
    },
    key2 => {
        parameter1 => 0,
        parameter2 => 1,
    },
}

given

my @rows = (
    [ 'key1', 0, 0 ],
    [ 'key2', 0, 1 ],
);

you want

$self->{$key}{parameter1} = $parameter;
$self->{$key}{parameter2} = $parameter2;

or

$self->{_ToolParameters}{$key}{parameter1} = $parameter;
$self->{_ToolParameters}{$key}{parameter2} = $parameter2;