perlrocks has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone, I have the following piece of code:
my @set_S; my @nset_S; my @epsilons; my $r=0; for $r (0..99){ $set_S[$r] = [$r]; } $q = 2; $sigma_square = 0.1 * $q; for my $err (0..$#set_S){ $epsilons[$err] = rand($sigma_square + 1); } my $t=0; for my $s (0..$#set_S){ print "@{$set_S[$s]}\t$epsilons[$s]\t"; @{$set_S[$s]} = @{$set_S[$s]} + $epsilons[$s]; print @{$set_S[$s]}, "\n"; $t++; }
The output looks like:
0 0.16702880859375 1.16702880859375 1 0.54862060546875 1.54862060546875 2 0.75128173828125 1.75128173828125 3 0.67547607421875 1.67547607421875 4 0.58304443359375 1.58304443359375 5 0.98953857421875 1.98953857421875 6 0.07342529296875 1.07342529296875 7 0.43919677734375 1.43919677734375 8 0.70689697265625 1.70689697265625
Apparently, my question is :Why is the addition wrong?? Why is perl turning the first columns to 1's when adding them to the second column?? How do i solve this? I appreciate your prompt response. Thanks

Replies are listed 'Best First'.
Re: Turning numbers to 1!
by moritz (Cardinal) on Jul 03, 2008 at 20:38 UTC
    @{$set_S[$s]} + $epsilons[$s];

    The first term here is an array. If you use an array in scalar context, it evaluates to the number of items in the array, which happens to be 1 in your case.

    If you just want to add the current index to the value, why not just say $s + $epsilons[$s]? Or if you want to access the first item of @{$set_S[$s]}, you can say $set_S[$s][0] + $epsilons[$s].

      Thanks a lot pal. Now i know why! Pheww! :-)
Re: Turning numbers to 1!
by alexm (Chaplain) on Jul 03, 2008 at 20:51 UTC
    Instead of
    $set_S[$r] = [$r];
    you can just say
    $set_S[$r] = $r;
    and then
    print "$set_S[$s]\t$epsilons[$s]\t"; $set_S[$s] = $set_S[$s] + $epsilons[$s]; print $set_S[$s], "\n";
    I don't see any reason to enclose $r on an anonymous array reference, at least in this context.
Re: Turning numbers to 1!
by jds17 (Pilgrim) on Jul 03, 2008 at 20:43 UTC
    In the line
    @{$set_S[$s]} = @{$set_S[$s]} + $epsilons[$s];
    the addition creates a scalar context for the right-hand side, in which
    @{$set_S[$s]} = 1.
    To get what you want, write
    @{$set_S[$s]} = $set_S[$s] + $epsilons[$s];
    instead.
      $set_S[$s] + $epsilons[$s];
      You forgot that $set_S[$s] is an array reference; moritz pointed out the right way to access the value.
        Thanks, you are right, I focused on the scalar context and did not finish to examine the expression correctly.