Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

i have the following code and am trying to select some data from a table which is then put into an array. i then want to put this array into a hash so that i can reference the data in a hash when i print my table and output it in the html as variables. if you could help that would be great. cheers here's the code.
my $sth5 = $dbh->prepare("select round, teamname, score from trees whe +re sport = ‘$sport’ and year = ‘$year’, order by round") || die "Can' +t prepare SQL get data statement"; $sth5->execute || die “can’t execute sql statement”; ##need to get all the data one row at a time from the table. my @row; while (@row = $sth5->fetchrow_array) { need to put each row into a hash. }

Replies are listed 'Best First'.
Re: appending an array to a hash
by Hot Pastrami (Monk) on Mar 22, 2001 at 02:42 UTC
    Assuming that the first column contains the value you want as the hash key, this would work:
    my @row; my %hash; while (@row = $sth5->fetchrow_array) { $hash{$row[0]} = \@row; }

    Update: Oops, merlyn pointed out my error. You'd want this instead:
    my %hash; while (my @row = $sth5->fetchrow_array) { $hash{$row[0]} = \@row; }
    Hot Pastrami
      if the selection from the database returns many rows how would i enter each row into the hash so that i can access each row element buy element and output them. so when i print the html
      <td> round1 team name</td>
      how can i reference the values??
        So you want each row to be stored in it's own hash, right? So if you've got 2 columns per row called "ID" and "value", you'd want to be able to access them like this?:
        my $value = $rows{$ID}{value}
        This sort of breakdown will require you to know all column names and what order they appear in, but that shouldn't be too hard. If you have the column names in an array, for instance, it would look like this:
        my @columns = ("ID","value","some_other_column"); my %rows; while (my @row = $sth5->fetchrow_array) { my %rowHash = (); for (my $i=0; $i < scalar @row; $i++) { $rowHash{$columns[$i]} = $row[$i]; } $rows{$row[0]} = \%rowHash; }
        Hope that helps...

        Hot Pastrami