Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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

Replies are listed 'Best First'.
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
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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://164301]
Approved by Rich36
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2018-02-19 19:04 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (266 votes). Check out past polls.