CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
a problem of subroutine

 



bettertony
New User

Apr 2, 2010, 12:49 AM

Post #1 of 3 (696 views)
a problem of subroutine Can't Post

here is a subroutine which i hope to call it from array adress
like SubName(/@a, /@b)
#############perl code############
#! usr/bin/perl
package tset;

sub ArraySum {
$in1=shift @_;
$in2=shift @_;
@in1=@$in1;
@in2=@$in2;
$i=0;
while (@in1 and @in2) {
$p=shift @in1;
$q=shift @in2;
@sum=$p+$q;
i+=1;
}
}
1;
###########code end##############

when run in another file (ArraySum(/@array1,/@array2)), error happens which seems to be into a died loop(i am not sure)
Can anyone told me the reason?Many thanks.


roolic
User

Apr 2, 2010, 2:09 AM

Post #2 of 3 (691 views)
Re: [bettertony] a problem of subroutine [In reply to] Can't Post

0. use strict and use my!
1. the array reference is \@array not /@array
2. type mismatch: @array = $x + $y (scalar)
3. sub returns nothing

package tset;
use strict;

sub ArraySum {
my( $in1, $in2 )=@_; # reading refernces
my @sum = (); # result initialising
while ( @{$in1} and @{$in2} ) {
push @sum, shift @{in1} + shift @{$in2}; # filling result
}
return wantarray ? @sum : \@sum;
}
1;

then calling:

use strict;
use tset;

my @res = ArraySum( \@arr1, \@arr2 ); # returns array
my $res2 = ArraySum( \@arr1, \@arr2 ); # returns the array reference

pay an attention:
the sub clears the input arrays via shifting data from array using the reference. to keep the input data untouched you have to use array index

my sub ArraySum {
my( $in1, $in2 )=@_; # reading refernces
my @sum = (); # result initialising
# getting max index if the input array are different by length;
my $max = scalar @{$in1} > scalar @{$in2} ?
scalar @{$in1} : scalar @{in2} ;
$max--;
foreach my $i ( 0 .. $max ) {
push @sum, $in1->[$i] + $in2->[$i]; # filling result
}
return wantarray ? @sum : \@sum;
}


7stud
Enthusiast

Apr 2, 2010, 11:04 AM

Post #3 of 3 (676 views)
Re: [bettertony] a problem of subroutine [In reply to] Can't Post

1) Search google for 'code tags'. Read the first 10 results and come back and post what you have learned.

2) Declare all variables with my(), e.g.:


Code
my $num; 
my @numbers;
my($num1, $num2) = (3, 4);
my %phone_number_for;


3)

Quote
ArraySum(/@array1,/@array2)), error happens


That isn't how you get a reference for an array. See perlreftut.


(This post was edited by 7stud on Apr 2, 2010, 11:06 AM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives