or ...
my $sql = qq| SELECT ID, tutorID, Latitude, Longitude, City, State, Zipcode FROM $table_tzips WHERE Zipcode IS not NULL ORDER BY tutorID |; my $last_tutor_id = ""; my $last_dist; my @tutors; my $sth = $dbh->prepare($sql); $sth->execute(); while (my $tzips = $sth->fetchrow_hashref()) { my $tutor_id = $tzips->{tutorID}; my $dist = calculate_distance( $clong, $clat, $tzips->{Longitude}, $tzips->{Latitude} ); if ($last_tutor_id ne $tutor_id) { $last_tutor_id = $tutor_id; push @tutors, $tzips; } else { next if $last_dist <= $dist; $tutors[-1] = $tzips; } $tzips->{Dist} = $last_dist = $dist; } my @report_fields = qw( tzipID ID Dist City State Zipcode ); for my $tutor ( sort{ $a->{Dist} <=> $b{Dist} } @tutors) ) { print(join(', ', @{$tutor}{@report_fields}), "\n"); }
In the OP case, where the full data has to be keep in memory for the final sorting, this approach may be just more complicated than ikegami's one and also imposes an extra load in the database.

But when you can output the data as you go and don't need to keep it in memory for a final processing stage, it may perform better, specially for large data sets, as it's memory usage is fixed O(1), not dependant on the data set size O(N).


In reply to Re^2: sorting an array of hashes and removing duplicates by salva
in thread sorting an array of hashes and removing duplicates by jmfees

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.