#!/usr/bin/perl -w use strict; my @source_data = ( [ 100, 204, 312 ], [ 102, 313, 409 ], [ 205, 206, 315 ], [ 207, 210, 314 ], ); my @sorted_numbers = sort map { @{$_} } @source_data; # Using hash for the lookup. If your N numbers are fairly dense over # 0..N then use an array for reduced mem consumption my %from_whence; foreach my $source_array (@source_data) { my $index = 0; foreach my $number (@$source_array) { $from_whence{$number} = [$source_array, $index]; ++$index; } }; # Look for 4 contig values my @recent; foreach my $number (@sorted_numbers) { push @recent, [ $number, $from_whence{$number} ]; next unless scalar @recent > 4; shift @recent; check_and_handle_contig(\@recent); } exit 0; sub check_and_handle_contig { my $numbers_info = shift; my $lastnum = undef; foreach my $numinfo (@$numbers_info) { my $num = $numinfo->[0]; if ($lastnum) { return unless $num == $lastnum + 1; } $lastnum = $num; } print "Found sequence:\n"; foreach my $numinfo (@$numbers_info) { my $num = $numinfo->[0]; my $info = $numinfo->[1]; print "$num from $info->[0]:$info->[1]\n"; } } #### Found sequence: 204 from ARRAY(0x814bc28):1 205 from ARRAY(0x8188e94):0 206 from ARRAY(0x8188e94):1 207 from ARRAY(0x8188ed0):0 Found sequence: 312 from ARRAY(0x814bc28):2 313 from ARRAY(0x8188c30):1 314 from ARRAY(0x8188ed0):2 315 from ARRAY(0x8188e94):2