Jean-Rene David wrote:
Hi,

Hello,

A little problem I encountered recently.

I have an array of integers and two indexes within
that array. I need to get another array identical
to the first one, except that all cells between
the two indexes (inclusive) must be compressed to
one column which is the sum of the originals
cells.

A program will illustrate below.

What I'm looking for is just a way to do the same
thing more elegantly. It has nested loops using
the same index variable and a duplicated test,
which are both a little ugly.

#!/usr/bin/perl

use warnings;
use strict;

my @array = qw{ 10 20 30 40 50 };
my $start = 1;
my $end   = 3;

my @out;
for( my $i = 0; $i < @array; $i++) {
    my $j;
    for( ; $i >= $start && $i <= $end; $i++) {
        $j += $array[$i];
        if( $i == $end ) {
            push @out, $j;
        }
    }
    push @out, $array[$i];
}

$\="\n";
print for @out;

The expected out is:
10
90
50

The second line contains the sum of elements 1, 2
and 3.

Here is one way to do it:

$ perl -le'
use List::Util qw/ sum /;

my @array = qw{ 10 20 30 40 50 };
my $start = 1;
my $end   = 3;

my @out = @array;
splice @out, $start, ( $end - $start ) + 1, sum @array[ $start .. $end ];

print for @out;
'
10
90
50



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.                            -- Larry Wall

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to