#!/usr/bin/perl use warnings; use strict; use Data::Dumper; #http://www.perlmonks.org/?node_id=1193467 my $aref = [1, 7, 6, 2, 2, 7, 1, 6, 99, 99,7,88, 7, 6,1,2,3]; my @result; my @stack = (); foreach my $candidate (@$aref) { if ($candidate == 6) # starting flag { push @stack,6; } elsif ($candidate == 7) #potential ending flag { if (@stack) { @stack=(); #throw away between 6, x, y, 7 } else { push @result, 7; # a singleton 7 was seen } } elsif (@stack) # inside of sequence starting with 6 { push @stack, $candidate; } else { push @result, $candidate; } } push @result, @stack if @stack; # unfinished sequence starting with 6? print Dumper \@result; __END__ prints: $VAR1 = [ 1, 7, 1, 88, 7, 6, 1, 2, 3 ];