in reply to Re^2: Generate Array of Hashes WITHOUT References
in thread Generate Array of Hashes WITHOUT References

$VAR1 = [ { 'Z' => '5', 'Y' => '4' }, $VAR1->[0] ];

The second element refers to the first element of the array reference. If $Data::Dumper::Deepcopy = 1;, then you will see that both array elements are the same.

The problem is of variable scoping; see Coping with Scoping. I will try to explain but do wait for better|clearer explanation.

Without my function, the hash %rec has scope file-wide (outside of the loop). The reference to the hash refers to that hash, the only copy. So modifying the only copy of the hash overwrites previous values (see by for { ... } print Dumper( \%rec ) ;). As the reference to the hash is saved twice, same values are repeated in Dumper() output.

Use of my function inside the while loop limits the scope of %rec within the loop. On each iteration a *spanking new* hash is allocated, saving the values as references to each separate hash in the array as expected.

Replies are listed 'Best First'.
Re^4: Generate Array of Hashes WITHOUT References
by tel2 (Pilgrim) on Sep 10, 2014 at 23:00 UTC
    Well explained, AF. Thanks for that!

    I tried $Data::Dumper::Deepcopy = 1;, and I see what you mean. One thing I don't understand is what you mean by:
      see by for { ... } print Dumper( \%rec ) ;
    I'd like to try that code, but what exactly should I type, coz the syntax doesn't look right yet?

      To start ...

      • ... means fill in the code as appropriate (and, author was too lazy to provide the whole thing not directly related to the point);
      • for { ... } is a reference to for loop code inside while loop;
      • then, print statement would go right after for loop.

      ... so  for { ... } print Dumper( \%rec ) ; expands to ...

      ... while ( <DATA> ) { ... for $field ( split ) { ... } print Dumper( \%rec ) ; push @AoH, \%rec; } ...