Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^3: Generate Array of Hashes WITHOUT References

by parv (Parson)
on Sep 10, 2014 at 14:34 UTC ( [id://1100155]=note: print w/replies, xml ) Need Help??


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; } ...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1100155]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2024-04-23 15:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found