use strict; use warnings; ... my $sql = qq| SELECT ID, tutorID, Latitude, Longitude, City, State, Zipcode FROM $table_tzips WHERE Zipcode IS not NULL |; my $sth = $dbh->prepare($sql); my %closest; $sth->execute(); while (my $tzips = $sth->fetchrow_hashref()) { my $tutorID = $tzips->{tutorID}; my $dist = calculate_distance( $clong, $clat, $tzips->{Longitude}, $tzips->{Latitude} ); next if $closest{$tutorID} && $closest{$tutorID}{dist} <= $dist; $closest{$tutorID} = { ID => $tutorID, tzipID => $tzips->{ID}, Dist => $dist, City => $tzips->{City}, State => $tzips->{State}, Zipcode => $tzips->{Zipcode}, }; } my @report_fields = qw( tzipID ID Dist City State Zipcode ); for my $tutor ( sort{ $a->{dist} <=> $b{dist} } values(%closest) ) { print(join(', ', @{$tutor}{@report_fields}), "\n"); }