in reply to Reading data from mySQL into hashes and manipulation of hashes

Greetings lagrenouille!

First off, I think some of the ugliness that you're stuck with here may be a result of the layout of the database that you're working with. It seems like it could use some more normalization, but without actually knowing the contents of the votes table I can only guess at it.

My guess is that the values in columns 5-10 (your hash keys) are some kind of label or identifier for choices that users vote on. Then the columns 11-16 contain the number of votes for the corresponding value in columns 5-10.

If you have any control over how this table looks, I would change it. Though only if you will be working with it frequently. There's nothing more annoying than a poorly formed database. It'll bite you in ways you never imagine when you start.

Regardless, there are ways that you can clean up the code in Section 1 above. First thing would be to NOT use "SELECT * ...". It doesn't tell you anything about what you're actually getting out of the table and you have to guess which position in the array holds the value you want to use. I highly recommend making a longer query that specifies exactly which columns you need. If you have to look at the code again in a month, will you remember the column configuration from that table? If you specify the columns you're selecting, you won't have to.

Next I would use some named variables to hold the values returned by your query. Pumping the row into an array is convenient, but as you've mentioned it's ugly, especially when dealing with 16+ columns. If I were coding this, I would use something like the following:

my ($choice1,$choice2,$choice3,$choice4,$choice5,$choice6); my ($votes1,$votes2,$votes3,$votes4,$votes5,$votes6); while( ($choice1, $choice2, $choice3, $choice4, $choice5, $choice6, $v +otes1, $votes2, $votes3, $votes4, $votes5, $votes6) = $sth_1->fetchro +w_array ) { . .

This will only work, of course, if you took my advice above and only selected the choice and votes columns that you need rather than doing SELECT *.

Populating the hash looks much nicer, too using these variables rather than the uninformative row array values:

%results = ( $choice1 => $votes1, $choice2 => $votes2, $choice3 => $votes3, . . );

YIKES, I wrote way too much! Hopefully some of it might be useful, somehow! I guess I just really don't want to get to work yet this morning.

~CubicSpline
"No one tosses a Dwarf!"