| |||||||||||
| |||||||||||
Array references Posted by Milo (Milo), 1 May 2003 I'd be grateful for any suggestions with some funny business that's happening with array references. I'm trying to extract whole rows from a postgresql database.With my record, it's probably a silly and obvious mistake, but here it is: $sth = $dbh->prepare($sql_string); $sth->execute or die "Cannot execute: " . $sth->errstr(); my @returned=(); while (@row = $sth->fetchrow_array) { push (@returned, \@row); } $sth->finish; print "RET: @returned\n"; return @returned; ...fills up @returned with a load of references, as one may expect. However, when I return to the main body of the program and try access the contents of these arrays, e.g. with this: foreach my $ret (@returned) { print "R1: $ret\n"; print "R2: " . @$ret . "\n"; } ...I get this: R1: ARRAY(0x81cd2c ![]() R2: 0 &c. Any suggestions would be welcome! Many thanks, Milo Thurston. Posted by admin (Graham Ellis), 1 May 2003 Hi, Milo ...Two things ... Firstly, you have not declared @row to be a my variable each time through the loop of fetchrow_array calls, so you're repeatedly pushing the SAME address onto the stack in @returned. The very last time at the while statement, an empty list is assigned to @row as there's nothing left for fetchrow_array to get from the result set. Conculsion - @returned is a long list of pointers to the same null list! Second, the . operator is used to concatanate strings and it works in a scalar context. If you concatante a list in this way, it will assume you mean the length of the list which (as the lists are all empty because of item 1 above) is zero. Solution: a) MY @row b) "R2: @$ret\n" Sample code showing the second problem solved: Code:
which runs as Code:
Posted by Milo (Milo), 2 May 2003 Firstly, you have not declared @row to be a my variable each time through the loop of fetchrow_array calls, so you're repeatedly pushing the SAME address onto the stack in @returned. Second, the . operator is used to concatanate strings and it works in a scalar context. Thanks, Graham. As I thought, they were silly mistakes. ![]() Milo. This page is a thread posted to the opentalk forum
at www.opentalk.org.uk and
archived here for reference. To jump to the archive index please
follow this link.
|
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho |