List of lists - baffled

H

Henry Law

I'm doing some simple list-of-lists processing, where the inner lists
are collections of field data from a database. I'm completely failing
to see some mistake I've made, probably an obvious one.

I can't post executable code because you can't replicate my environment
(the database and so forth) but I'm posting a sample case and the
console output from it, and you'll see where I'm stuck. (The example
below is from ActiveState Perl but the same problem happens under Linux)

# ------------------ tryit.pl --------------------------
#! /usr/bin/perl
use strict;
use warnings;

# "use" statements omitted for clarity; they export "%globals".
use DBI;
use Data::Dump qw(dump);

my @hosts = ();

my $hdbh = db_connect(\%globals); # Opens MySQL connection via DBI/DBD
my $hsth = $hdbh->prepare("SELECT host_name,id FROM host;");
$hsth->execute;
while (my $array_ref = $hsth->fetchrow_arrayref) {
print "\$array_ref:",dump($array_ref),"\n";
push @hosts,$array_ref;
print "\@hosts:",dump(@hosts),"\n";
}
$hsth->finish;

# ------------------ results from console --------------------
F:\>tryit.pl
$array_ref:["foo", 1]
@hosts:["foo", 1]
$array_ref:["main-atx", 2]
@hosts:do {
my $a = ["main-atx", 2];
($a, $a);
}

The second array reference looks to be in /exactly/ the same format as
the first, and when the first is pushed onto the outer list all looks
OK, yet when the second array ref is pushed onto the list everything
goes haywire. Help?
 
H

Henry Law

From the documentation for fetchrow_arrayref (perldoc DBI):

Note that the same array reference is returned for each fetch, so
don't store the reference and then use it after a later fetch.

Ohhhh ... I never looked at the DBI documentation when debugging this.
Now I see what's happening and can fix it easily. Thank you very much.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top