Problems? Is your data what you think it is? PerlMonks

 on Aug 29, 2002 at 14:38 UTC Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How do you implement a subprogram that adds two integer arrays together. It must have only two parameters, which are the two arrays to be added. The second array will also hold the sum array on exit from the subprogram.

Replies are listed 'Best First'.
by Abigail-II (Bishop) on Aug 29, 2002 at 14:57 UTC
Smells like homework to me. Anyway,
```use strict;
use warnings;

sub adder (\@\@) {map {\$_ += \$_ [0] [\$_ [2] ++]} @{\$_ [1]}}

my @one = (1, 2, 3, 4,  5);
my @two = (6, 7, 8, 9, 10);

print "@two\n";
__END__
7 9 11 13 15
Explaining how it works is left as an exercise for the reader.

Abigail

by Zaxo (Archbishop) on Aug 29, 2002 at 14:50 UTC

PDL does this kind of thing very well:

```perl -MPDL -e'\$foo = pdl [1..3];\$bar = pdl [5..7];\$bar += \$foo; print
+\$bar,\$/'
[6 8 10]
\$

After Compline,
Zaxo

by Notromda (Pilgrim) on Aug 29, 2002 at 14:54 UTC
This sounds a lot like a homework project, so I'm not going to write the entire thing. but it sounds like when you call your subroutine, you need to pass it references to your arrays:
```my @one = (1,2,3,4);
my @two = (6,7,8,9);

by fruiture (Curate) on Aug 29, 2002 at 14:48 UTC

Specify "adds two integer arrays together"! What should it do?

--
http://fruiture.de
by theorbtwo (Prior) on Aug 30, 2002 at 03:44 UTC

You could try doing this:

```use warnings;
use strict;

my @array1=(1, 2, 0);
my @array2=(1, 1, 1);

my (\$a1, \$a2) = @_;
@\$a2=@\$a1+@\$a2;
}

print @array2;

Warnings: Perl monks may behave like satinists, but only when (@{[localtime]})==9.

Confession: It does an Immortal Body good.

Create A New User
Node Status?
node history
Node Type: perlquestion [id://193784]
help
Chatterbox?
 [bounim]: yo

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2018-01-21 22:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How did you see in the new year?

Results (230 votes). Check out past polls.

Notices?