use Data::Dumper; my $allow_loose6 = 1; my $aref = [1, 6, 2, 2, 7, 1, 6, 99, 99, 7]; my @new = (); my @loose = (); my $flag = 0; for (@$aref) { $flag = 1 if (!$flag and $_==6); if (!$flag) { push @new, $_; } else { push @loose, $_; } if ($flag and $_==7) { $flag = 0; @loose = (); } } $aref = \@new; if ($allow_loose6) { push @$aref, @loose; } elsif (@loose) { die "Unterminated 6 detected"; } print Dumper $aref