Search code examples
perlperl-data-structures

Inserting element to hash of hashes in perl


I have an array. The elements in the array are containing semi colon in between them.

Array looks something like this:

@Array = { "AUT;E;1",
           "AUT;E;2",
           "CHE;A;1",
           "CHE;C;4"
         };

I want to split the array elements using ';' (semicolon) as delimiter.

By using hash of hashes I want to store 'AUT' as key and under that want to store E => 1 and E => 2.

i.e I needed the hash as

%HashOfElem = (
         'AUT' => {
                     'E' => 1,
                     'E' => 2
                  },

         'CHE' => {
                     'A' => 1,
                     'C' => 4
                  }
              )

For that purpose I wrote the following code which is not behaving as expected :(

foreach(@Array)
{
    my @TmpArray = split(/;/,$_);

    %HashOfElem = (
              $TmpArray[0] => {
                                  $TmpArray[1] => $TmpArray[2]
                              }
                  );

}

If my approach is wrong then which data structure in perl can be used to achieve above purpose?

Please help..


Solution

  • Note that you're doing wrong assignement to @Array, it should be (parenthesis instead of braces):

    updated according to comment:

    my @array = (
        "AUT;E;1",
        "AUT;E;2",
        "CHE;A;1",
        "CHE;C;4"
    );
    

    so your script becomes:

    my @array = (
        "AUT;E;1",
        "AUT;E;2",
        "AUT;E;2",
        "CHE;A;1",
        "CHE;C;4"
    );
    my %hash;
    my %dups;
    foreach (@array) {
        next if exists $dups{$_};  # skip this line if already stored
        $dups{$_} = 1;
        my @tmp = split/;/;
        push @{$hash{$tmp[0]}{$tmp[1]}}, $tmp[2];
    }
    say Dumper\%hash;
    

    output:

    $VAR1 = {
              'CHE' => {
                         'A' => [
                                  '1'
                                ],
                         'C' => [
                                  '4'
                                ]
                       },
              'AUT' => {
                         'E' => [
                                  '1',
                                  '2'
                                ]
                       }
            };