----- Original Message ----- 
From: "Rob Dixon" <[EMAIL PROTECTED]>
To: "Sui Ming Louie" <[EMAIL PROTECTED]>; <[EMAIL PROTECTED]>
Sent: 08 May 2004 11:07
Subject: Re: Function to Add Two Arrays


> 
> Hi.
> 
> See my answer in-line.
> 
> Sui Ming Louie wrote:
> >
> 
> > I am trying write a function that adds (not merges) two arrays and return an
> > array.  This is my first attempt:
> > 
> >  
> > 
> >  
> > 
> >   sub add_arrays (@ @) {
> 
> A subroutine prototyped like this can't separate the two arrays as
> their contents just appear in one long list. In this case
> (1, 2, 3, 2, 4, 6). You need to pass the two parameters as array
> references, so either change the prototype to
> 
>   sub add_arrays ([EMAIL PROTECTED]@) {
>     :
>   }
> 
> or remove the prototype altogether and call it as
> 
>   @array_sum = add_arrays ([EMAIL PROTECTED], [EMAIL PROTECTED]);

Much better idea! Prototypes are bad news. The advice from most
Perl celebrities is to avoid prototypes completely. They are quirky,
confusing, and lead to buggy code. 

Perl 6 will be getting something much better, but you probably won't
want to wait that long ;).

> 
> >     my (@array1, @array2) = @_;
> 
> Now you'll need
> 
>   my @array1 = @{$_[0]};
>   my @array2 = @{$_[1]};
> 
> 
> >     for (my $xx = 0 ; $xx <= $#array1 ; $xx++) {
> 
> This is more neatly written as
> 
>   foreach my $xx (0 .. $#array1) {
>     :
>   }
> 
> >       $array1[$xx] += $array2[$xx];
> > 
> >     } # for
> > 
> >  
> > 
> >     return @array1;
> > 
> >  
> > 
> >   }  # add_arrays
> > 
> >  
> > 
> >   my @array_one = (1,2,3);
> > 
> >   my @array_two = (2,4,6);
> > 
> >   my @array_sum;
> > 
> >  
> > 
> >   @array_sum = add_arrays (@array_one, @array_two);
> > 
> >   print @array_sum;
> 
> Change this to
> 
>   print "@array_sum\n";
> 
> to separate elements with spaces.

You need to set $" = ' ' for this to add spaces.

Alternatively:

print join(' ',@array_sum),"\n";


_______________________________________________
ActivePerl mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to