use strict; my @rowTypes = (1, 2, 3, 3, 3, 1, 2, 3, 3, 1, 2, 1, 3); my $count; for my $rowType (@rowTypes) { if ($rowType == 1) { # New group next unless defined $count; # No processing for first or empty group print "$count "; $count = 0; # Reset count. Set to undef to skip empty group next; } ++$count if $rowType == 3; } print "$count " if defined $count; # Need to process the last group