Hi,

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.

Thanks for any input,

-- 
JR

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


Reply via email to