my @questions; my %pending; $sth = $dbh->prepare("SELECT id, question FROM questions"); $sth->execute(); $sth->bind_columns(\@pending{qw(id question)}); while($sth->fetch) { my $sth = $dbh->prepare("SELECT answer, is_correct FROM answers WHERE to_question = ?"); $sth->execute($pending{id}); $sth->bind_columns(\@pending{qw(answer is_correct)}); while($sth->fetch) { if($pending{is_correct}) { $pending{correct_answer} = $pending{answer}; } else { ## Add to array of wrong answers push @{$pending{wrong}}, $pending{answer}; } } push @questions, %pending; } return @questions;