MySql - push a hash into an array

MySql - push a hash into an array

Post by John » Wed, 04 Oct 2006 02:43:27


Hi

I am reading a row of hashes from a MySQL table.
I need to add that row to an array to create an 'array of hashes'
I should then be able to access, say, $xyz[34]{'steel'}.

The following is part of the code:

my @xyz=({}); # array of hashes

$sql="SELECT coal,iron,steel,china,wool,cloth,fish,livestock FROM industry";
$sth=$dbh->prepare($sql);
$sth->execute or die "Unable to execute query: $dbh->errstr\n";

my $row;
while ($row = $sth->fetchrow_hashref) {push (@xyz,$row)}

$sth->finish();
$dbh- >disconnect();

print $xyz[6]{'cloth'};

The print statement is empty. Any ideas?

Regards
John
 
 
 

MySql - push a hash into an array

Post by Paul Lall » Wed, 04 Oct 2006 02:55:05


There is no need for that initialization. Indeed, it will hurt you in
the long run. You are specifically adding one completely empty hash
reference to your array. Therefore, when all is said and done, your
array will have one more hash than the number of rows in your data set.
Change to:
my @xyz;



Well the first and most obvious is: Are you sure that the statement
handler returned at least 7 rows? The second and second-most obvious
is: Are you sure that the 7th row's value for the 'cloth' column was
neither NULL nor the empty string?

What do you get for these two lines?

use Data::Dumper;
print Dumper(\@xyz);

Finally, are you aware that DBI has a means by which to do this
already?
my @xyz = @{ $sth->fetchall_arrayref( { } ) };

Paul Lalli

 
 
 

MySql - push a hash into an array

Post by reading ne » Wed, 04 Oct 2006 03:33:25


Just this
my @xyz;
will do.


Use Data::Dumper to see what is in @xyz. Perhaps there is no seventh
element.


--
Posting Guidelines for comp.lang.perl.misc:
http://www.yqcomputer.com/ ~tadmc/clpmisc/clpmisc_guidelines.html
 
 
 

MySql - push a hash into an array

Post by John » Wed, 04 Oct 2006 17:04:31

Thank you, gentlemen.

I can now see my mistake.

It's proably better to use the fetchall construct.

Thanks again and regards
John