Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Re: Hash of hashes syntax

by bwana147 (Pilgrim)
on Mar 19, 2003 at 08:41 UTC ( [id://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

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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://244284]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-12-07 18:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which IDE have you been most impressed by?













    Results (50 votes). Check out past polls.