use strict; use warnings; my @list = (1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1); my @targets = (5, 8, 42); my %addresses; push @{$addresses{$list[$_]}}, $_ for 0 .. $#list; for my $target (@targets) { if (! exists $addresses{$target}) { print "There are no entries for $target\n"; next; } print "Target $target\n"; my @targetList = @{$addresses{$target}}; for my $address (@targetList) { my $last = $address + 3 < $#list ? $address +3 : $#list; print ' ', join ', ', @list[$address + 1 .. $last]; print "\n"; } } #### Target 5 6, 7, 8 4, 3, 2 Target 8 9, 8, 7 7, 6, 5 There are no entries for 42