On Jun 19, 11:41 am, [EMAIL PROTECTED] (Jean-Rene David) wrote:
> 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,

#!/usr/bin/perl
use warnings;
use strict;
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]);

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


For more information:
perldoc -f splice
perldoc List::Util

Hope that helps,
Paul Lalli


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


Reply via email to