@a = qw/1 1 0 3 8 9 5 2 0 12 2 1/; $m = 5; print "@a\n"; for $x (0 .. $#a){ if($a[$x] < $m){$a[$x+1] += $a[$x]; next;} if($a[$x+1] < $m and $x < $#a){$a[$x+1] += $a[$x]; next;} push @b, $a[$x]; } print "@b\n"; #### 1 1 0 3 8 9 5 2 0 12 2 1 5 8 9 7 15 #### @a = qw/1 13 0 3 8 9 5 2 2 0 1 0 2 0 2 1 13 1/; $m = 5; grep $s += $_, @a; while ($s > $m){ $e = shift @a; if($e >= $m){ $s -= $e; push @b, $e; } else { $a[0] += $e;} } $s < $m ? $b[$#b] += $s : push @b, $s; print "@b\n";