Home Ask Login Register

Developers Planet

Your answer is one click away!

LyChn February 2016

How to integrate a loop in another loop in Perl

For the code below I am trying to include another loop into the foreach statement. I have two lists. The first one "item" is my list where I check the elements if they are zero or not. The second list "varis" is my list where the values are saved for the case the values are not zero.

I want to check if the values in my list "item" are zero, if so set the elements as zero. If not set the value of the first element as the first value listed in my list varis. Same goes for the second element. If the second element is not zero set the value as the second value listed in varis and so on. So far I used the foreach statement to check my elements of my "item" list. However I'm not sure how to go about my second list. I am thinking about integrating a second loop into my foreach statement. But I don't know how.

$sums = (2+4+5+6+5+10+4); 
my @item=(0,50,5,3,5,15,0);
$sum = 0;
my @varis = (2,4,5,6,5,10,4);

foreach my $item(@item){
        if ( $item==0) {$item=0}    # if element in item is zero set element as zero
           else {$item=$varis;}     # else for element in @item set the value as the first element in @varis, for the second element (if it's not zero) in @item add the second element and so on     
       $sum = $sum + $item;         # sum all the values

    $result = $sums/$sum;
    print "$result\n";


ikegami February 2016

You want $varis[$i] where $i is the index of the element of @items being processed, but you don't have $i. As such, you need to iterate over the indexes of @items instead of iterating over its elements.


my $sum = 0;
for my $i (0..$#items) { 
   my $item;
   if ($items[$i] == 0) {
      $item = 0;
   } else {
      $item = $varis[$i];

   $sum = $sum + $item;

Simplified solution:

my $sum = 0;
for my $i (0..$#items) {
    $sum += $varis[$i] if $items[$i];

Post Status

Asked in February 2016
Viewed 1,717 times
Voted 5
Answered 1 times


Leave an answer

Quote of the day: live life