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

My USD .02 :
@a=qw(1 2 3 4); @b=qw(1 2 3 4); @c=(); $c[@c] = $a[@c] + $b[@c] while defined $a[@c] and defined $b[@c]; print "@c \n";
It's not very readable though - frankly, I'd stick with the one you're already using!

andy.

Replies are listed 'Best First'.
Re: Re: Summing the elements of multiple arrays into a new array
by mull (Monk) on Oct 31, 2001 at 23:37 UTC

    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...

      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