#!/usr/bin/env perl -l use strict; use warnings; use List::Util qw{first}; my $min = 3; my @records = reverse(0 .. 10, 13, 17, 42); print "All records: @records"; my %deleted; for my $i (0 .. $#records) { my $top_index = first { ! $deleted{$_} } $i .. $#records; last unless defined $top_index; my $top = $records[$top_index]; my @group = ($top); for ($top_index + 1 .. $#records) { next if $deleted{$_}; if (compare_sub($top, $records[$_]) <= $min) { push @group, $records[$_]; ++$deleted{$_}; } else { last; } } ++$deleted{$top_index}; print "Group: @group"; } sub compare_sub { my ($x, $y) = @_; return abs($x - $y); } #### All records: 42 17 13 10 9 8 7 6 5 4 3 2 1 0 Group: 42 Group: 17 Group: 13 10 Group: 9 8 7 6 Group: 5 4 3 2 Group: 1 0