Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much


by Anonymous Monk
on Aug 29, 2002 at 10: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.

Replies are listed 'Best First'.
Re: adder
by Abigail-II (Bishop) on Aug 29, 2002 at 10: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.


Re: adder
by Zaxo (Archbishop) on Aug 29, 2002 at 10: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,

Re: adder
by Notromda (Pilgrim) on Aug 29, 2002 at 10: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 fruiture (Curate) on Aug 29, 2002 at 10:48 UTC

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

Re: adder
by theorbtwo (Prior) on Aug 29, 2002 at 23: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?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2019-12-10 07:26 GMT
Find Nodes?
    Voting Booth?

    No recent polls found