Home > Enterprise >  Looping through a perl array
Looping through a perl array

Time:10-23

I am trying to: Populate 10 elements of the array with the numbers 1 through 10. Add all of the numbers contained in the array by looping through the values contained in the array.

For example, it would start off as 1, then the second number would be 3 (1 plus 2), and then the next would be 6 (the existing 3 plus the new 3) This is my current code

#!/usr/bin/perl
use warnings;
use strict;
my @b = (1..10);
for(@b){
    $_ = $_ *$_ ; 
}
print ("The total is: @b\n")

and this is the result

The total is: 1 4 9 16 25 36 49 64 81 100

What im looking for is:

The total is: 1 3 6 10 etc..

CodePudding user response:

The shown sequence has for each element: its index 1 value at the previous index

perl -wE'@b = 1..10; @r = 1; $r[$_] = $_ 1   $r[$_-1] for 1..$#b; say "@r"'

The syntax $#name is for the last index in the array @name.

If the array is changed in place, as shown, then there is no need to initialize

perl -wE'@b = 1..10; $b[$_] = $_ 1   $b[$_-1] for 1..$#b; say "@b"'

Both print

1 3 6 10 15 21 28 36 45 55

As a script

use warnings;
use strict;
use feature 'say';

my @seq = 1..10; 

for my $i (1..$#seq) {
    $seq[$i] = $i 1   $seq[$i-1]; 
}

say "@seq";
  • Related