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; }