Posted by Milo (Milo), 1 May 2003I'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();
while (@row = $sth->fetchrow_array)
push (@returned, \@row);
print "RET: @returned\n";
...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:
Any suggestions would be welcome!
Posted by admin (Graham Ellis), 1 May 2003Hi, 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.
a) MY @row
b) "R2: @$ret\n"
Sample code showing the second problem solved:
which runs as
Posted by Milo (Milo), 2 May 2003Firstly, 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.
As I thought, they were silly mistakes.
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: email@example.com • WEB: http://www.wellho.net • SKYPE: wellho