Search code examples
perlperl-data-structures

cant get array of hashes in perl


I have the Employees CSV Data and i try to insert each employee hash in to an array

open($empOutFh,">empOut.txt")
    $hash= [];
    while(<$empFh>) {
        @columnNames = split /,/, $_ if $.==1;
        @columnValues = split /,/, $_;
        %row = map{$_=>shift @columnValues}@columnNames;
        push @$hash,\%row;
    } 
    print Dumper($hash);

I am getting the output has

$VAR1 = [
          {
            'emp_no' => '11000',
            'hire_date
' => '1988-08-20
',
            'birth_date' => '1960-09-12',
            'gender' => 'M',
            'last_name' => 'Bonifati',
            'first_name' => 'Alain'
          },
          $VAR1->[0],
          $VAR1->[0],
          $VAR1->[0]
      ]

But when i am try to print each row it showing different row hash for each time


Solution

  • The problem is that you're using a single hash %row, so \%row is always referring to the same hash. Every time you assign to %row, you're not setting it to a new hash, you're just clearing out the same hash and repopulating it (thereby affecting, indirectly, every element of your array).

    To fix this, you need to create a new hash in each loop iteration. The minimal change to your code would be to declare %row as a lexical variable with local scope, by using the my operator:

            my %row = map { $_ => shift @columnValues } @columnNames;
            push @$hash, \%row;
    

    Another option is to eliminate the intermediate variable entirely, and just generate a reference to a new anonymous hash on each pass:

            push @$hash, { map { $_ => shift @columnValues } @columnNames };