Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Re: Hash of hashes syntax

by bwana147 (Pilgrim)
on Mar 19, 2003 at 08:41 UTC ( #244284=note: print w/ replies, xml ) Need Help??


in reply to Re: Hash of hashes syntax
in thread Hash of hashes syntax

I'm afraid your last solution, as concise as it might be, simply does not work. \%h always refers to the same hash. You may well change its content at each loop, you're always modifying the same hash, and all members of %hash_of_hashes refer to it.

You really must create a new hash at each loop. This will do it:

$hash_of_hashes{$rn} = { %h };
(the hash keys and values are flattened into a list, which in turn is used to create an anonymous hash).

--bwana147


Comment on Re: Re: Hash of hashes syntax
Select or Download Code
Replies are listed 'Best First'.
Re: Re: Re: Hash of hashes syntax
by Enlil (Parson) on Mar 19, 2003 at 09:19 UTC
    I'm afraid your last solution, as concise as it might be, simply does not work. \%h always refers to the same hash

    Not true.

    In this case, it would refer to a different hash. This is because the variable my %h is lexically scoped, and thus it is recreated each time through the loop, and so \%h will point to a different hash each time through the loop. To illustrate what I mean here is some code:

    The differences are subtle, but jdporter's code works.

    -enlil

Re: Re: Re: Hash of hashes syntax
by Chmrr (Vicar) on Mar 19, 2003 at 09:24 UTC

    Good eye, but this actually isn't a problem in this case. Because of the my %h inside of the loop, %h is a different (and new) lexical through each iteration -- thus there is no problem just sticking a reference to it into the hash or array. The problem comes from code like this (nearly directly copied from perldsc):

    my %hash; for $i (1..10) { %hash = somefunc($i); $hash_of_hashes{$rn} = \%hash; # WRONG! }

    Note where the "my" is. See perldsc or perlreftut or perllol for more.

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (11)
As of 2015-07-30 08:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (270 votes), past polls