I have a data that looks like this:
3
2
1
5
What I want to get is the "decreasing" cumulative of this data yielding
11
8
6
5
0
What is the compact way of doing that in Perl?
I have a data that looks like this:
3
2
1
5
What I want to get is the "decreasing" cumulative of this data yielding
11
8
6
5
0
What is the compact way of doing that in Perl?
perl -e '{ my @a = (3,2,1,5); map { $s+=$_ } @a;
map { print "$s\n"; $s-= $_ } (@a,0) }'
or
perl -e '{ my @a = (3,2,1,5); my @r = (0);
map { $s += $_ ; push @r, $s } reverse @a;
print join("\n", reverse @r)."\n" }'
Note: these both require an extra statement my $s=0;
using strict
.
But may I ask WHY?
I am not sure if you can get more compact than @DVK's solution.
#!/usr/bin/perl
use strict; use warnings;
use List::Util qw(sum);
my @array = (3, 2, 1, 5);
my $sum = sum @array;
for my $x ( @array ) {
print $sum, "\n";
$sum -= $x;
}
print "0\n";
Combining sum
with map
:
#!/usr/bin/perl
use strict; use warnings;
use List::Util qw(sum);
my @array = (3, 2, 1, 5);
my $sum = sum @array;
print join("\n", map $sum -= $_, (0, @array)), "\n";
Here you go
#!/usr/bin/perl -w
use strict;
use List::Util qw (sum);
my @a = ( 3,2,1,5);
my $sum = sum(@a);
foreach ( @a )
{
print "$sum ";
$sum -= $_;
}
print $sum;
perl -e 'print join(", ", reverse map { $s=$s+$_ } reverse qw/3 2 1 5 0/)'