my %order; while ( my $rec = $data->fetchrow_hashref ) { push @{ $result{ $rec->{"ID"} } }, $rec->{"item"}; push @order, $rec->{ID}; # read order } #### my $last = $order[0]; # first key for my $cur ( @order[1..$#order] ) { # following keys compare($last,$cur); $last = $cur; # keep current as last } #### sub compare { my ($previous,$present) = @_; ... }