@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";