$sth = $dbh->prepare("Select * FROM datatable"); $sth->execute; my %map; { my @col = @{ $sth->{NAME_lc} }; for (0..$#col) { $map{$col[$_]} = $_ } } while( my $row = $sth->fetchrow_arrayref ) { # I want the cols named ID, name, city, in that order printf "%d: %s from %s\n" ,$row->{$map{id}} ,$row->{$map{name}} ,$row->{$map{city}}; }