in reply to Re: Summing the elements of multiple arrays into a new array
in thread Summing the elements of multiple arrays into a new array

That is a pretty cool looking solution there andye, but shouldn't you use or instead of and, to account for cases where one array may have greater length than the other, as the other responses do? I can't help but point out that as written, your solution only works in the special case where both arrays have the same number of elements...

  • Comment on Re: Re: Summing the elements of multiple arrays into a new array

Replies are listed 'Best First'.
Re: Re: Re: Summing the elements of multiple arrays into a new array
by andye (Curate) on Nov 01, 2001 at 17:37 UTC
    mull, you're absolutely right. The reason I didn't was that I assumed the compiler would squeal about undefined values if I tried to add a value that didn't exist. But of course it doesn't - what with this being Perl, and all. ;)

    So

    $c[@c] = $a[@c] + $b[@c] while defined $a[@c] or defined $b[@c];

    andy.

      If you have -w or use warnings turned on, you'll get the following error when the arrays aren't the same size:
      Use of uninitialized value in addition (+)
      Which is the most irritating non-warning that perl can toss at you. Its complaining about something like (3 + undef) which is a perfectly valid Perl expression, so I wish perl wouldn't yell at me for using it.

      p.s. my solution above also spits out the same spurious warnings...

      -Blake

        It's a good warning in the sense that sometimes you will have variables that you intended to set get into your assignments still undefined and this lets you know, in a non-fatal way, that something may be wrong.

        On the other hand, you can do like the Slashdot crew and customize a SIGWARN callback to muffle this output.