How can I get a decreasing set of frequency series with Perl?

I have data that looks like this:

3
2
1
5

What I want to get is the “reduction" of cumulative data by getting

11
8
6
5
0

What is the compact way to do this in Perl?

+3
source share
4 answers
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: for both, they require an additional operator my $s=0;with strict.

But may I ask WHY?

+7
source

I'm not sure if you can get a more compact solution than @DVK.

#!/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 sumwith 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";
+6
source

   #!/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;
+2
perl -e 'print join(", ", reverse map { $s=$s+$_ } reverse qw/3 2 1 5 0/)'
+1

Source: https://habr.com/ru/post/1738116/


All Articles