my $positions = undef; my @segment=(); foreach (0..$#probs){ if ($probs[$_]>0.5 && $probs[$_+1]>0.5){ $positions = $positions.','.$_; } else {push @segment, $positions if ($positions); $positions = undef} }