How about this? It seems to do you what you want, at least for the given test data.
use v5.16;
use warnings;
# collapse a list
my @data = (0, 3, 8, 9, 5, 2, 0, 1, 0);
my $acc = 0;
say join(',',@data);
while (@data && $data[0] < 5) {
$acc += shift @data;
}
$data[0] += $acc;
$acc = 0;
while (@data && $data[$#data] < 5) {
$acc += pop @data;
}
$data[$#data] += $acc;
say join(',',@data);
BUT, what do you want to happen if the accumulated total become more than 5? i.e if the list starts (2,2,2,7,...) should the result be (13,...) or (6,7,...) or don't you care?