my $sql = qq(select * from table order by id); my $data_col = $dbh->selectcol_arrayref($sql, { Columns => [ 2, 3 ] }); my %seen; my @list = @$data_col; while (@list){ my $line_n = shift @list; my $word = shift @list; if ($seen{$line_n}++) { print " "; } else { print "\n$line_n - "; } print $word; }