in reply to Help with manipulating data from a database??

I would think that doing as much of the work as possible in the SQL query, as suggested by other Monks, makes most sense. I have not done enough SQL to usefully contribute there. Looking at the documentation for DBI I saw the fetchall_arrayref method. If going the simple query route, you could use it to populate a hash keyed by service_id with the results of the query sorted by descending distance. Thus the shortest distance row for each service would be assigned to the hash last, overwriting any longer distances. I don't have DBI available (or a database for that matter) so have made up a pretend routine that returns a ref. to an AoA and I added a little more pretend data.

use strict; use warnings; use Data::Dumper; sub pretendFetch { my $cannedFetch = [ [6200249230, 2, 247.695377429616], [6200200581, 1, 131], [6200249220, 2, 394.81641303269], [6200249240, 2, 148.32734070292], [6200249269, 1, 127.84583439484], [6200249250, 2, 394.507287638644], [6200248437, 1, 234.38349845484], ]; return $cannedFetch; } my %service_id = map { $_->[1] => { stop_reference => $_->[0], distance => $_->[2] } } sort { $b->[2] <=> $a->[2] } @{ pretendFetch() }; print Data::Dumper->Dump([\%service_id], [q{*service_id}]);

Which produces

%service_id = ( '1' => { 'distance' => '127.84583439484', 'stop_reference' => '6200249269' }, '2' => { 'distance' => '148.32734070292', 'stop_reference' => '6200249240' } );

I hope this is of interest.

Cheers,

JohnGG