my $select = $db->prepare('SELECT line_n, word, word_position FROM text'); $select->execute; my $text; while (my ($line, $word, $pos) = $select->fetchrow_array) { $text->{$line}[$pos - 1] = $word; } print Dumper($text);