Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

overwriting references in a loop

by toadi (Chaplain)
on May 06, 2002 at 12:13 UTC ( #164301=perlquestion: print w/ replies, xml ) Need Help??
toadi has asked for the wisdom of the Perl Monks concerning the following question:

I have a hash. with is filled with key value/pairs. In this hash I have one key: a array_ref with is also filles with hash references.
So I fetch the data for these hashes and fill the array:
my @array1; while( $sth->fetch ) { my %fetch2; $fetch2{username} = $username; $fetch2{accountid} = $accountid; $fetch2{statusid} = $statusid; print "$username - $accountid - $statusid \n"; push (@array1, \%fetch2); } $fetch1{array_ref} = \@array1; return \%fetch1;
Now my question is: Can I be sure that one of the hash references can be overwritten by another one when declaring them at the start of the while??? And if so can I solve this problem in a better way???

--
My opinions may have changed,
but not the fact that I am right

Edit kudra, 2002-05-06 Changed title

Comment on overwriting references in a loop
Download Code
Re: references
by BUU (Prior) on May 06, 2002 at 12:27 UTC
    It might make a bit more sense to just use hashkeys with in the second array.. i.e. $array1[0]{username}=$username etc. Also note that your pushing a refference to an array
    $fetch1{array_ref} = \@array1;
    This is pointing to @array1 specifically, if you just wanted an annonymous array, then drop the backslash, and (if you need to) surround it with parens.
Re: Pushing References
by tadman (Prior) on May 06, 2002 at 14:26 UTC
    Before you get too sidetracked, you might want to look at the DBI call selectall_hashref() which returns a hash based on a key field.

    As to your references being overwritten, here is an example of the wrong way:
    my @foo; my %bar; while ($sth->fetch()) { @bar{'name','age'} = ($name, $age); push (@foo, \%bar); }
    This uses the same hash each time, so your array actually contains duplicates. In your example you are declaring it specifically each time, so each %fetch2 is unique. Summary: Declared inside means unique, outside means recycled.

    s/\?+/\?/g;   # BTW

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (8)
As of 2015-07-03 03:15 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 (47 votes), past polls