Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

adder

by Anonymous Monk
on Aug 29, 2002 at 14:38 UTC ( #193784=perlquestion: print w/ replies, xml ) 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.

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

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

    --
    http://fruiture.de
Re: adder
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

Re: adder
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); &adder(\@one,\@two);
Re: adder
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); adder @one => @two; print "@two\n"; __END__ 7 9 11 13 15
    Explaining how it works is left as an exercise for the reader.

    Abigail

Re: adder
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); sub addarrays { my ($a1, $a2) = @_; @$a2=@$a1+@$a2; } addarrays(\@array1, \@array2); print @array2;

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


    Confession: It does an Immortal Body good.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://193784]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (10)
As of 2014-09-02 17:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (25 votes), past polls