Plexus Plexus - 4 days ago 5x
Perl Question

perl, populating a hash from a subroutine call on file input, array input, or no input

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 or array to populate the hash and call it as follows:

from an array: $Object->ImportData(\@Arraylist);
from a textfile: $Object->ImportData(textfile.csv);

in this function ImportData, I would like to read my key from an array list which will strictly be the ID#, or from the CSV file, it'd be strictly the first column that is the ID# or to be able to insert the values manually:

The ID number is to be the key.

I'm thinking of also generating at least one parameter field for this key by default, and assigning it a default value 0.

Basically when I return from this list I'll have something suggested by ikegami earlier, like:

$self->{_ToolParameters}{$ID#1}{test_parameter_1} = $value;
$self->{_ToolParameters}{$ID#2}{test_parameter_1} = $value;

The problem becomes for me the subroutine, differentiating whether I obtain a textfile, or an array, or whether the subroutine was called without parameters. I want the subroutine to know what parameter type was entered, and assign the hash value appropriately

sub ImportData {

if(array case)
{ #takes each element of the array, where the array is just an array of the keys

else if(file case)
{ #takes the first column of a csv file

#input ID's manually with STDIN


I'm new to perl, and accustomed to C, so I'm having difficulty accessing what was passed into the subroutine from when it was called, anyone have ideas on how to differentiate these different input types?


It's unclear what you want.

To produce

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


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

you want

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


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