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:
addition in subroutines

 



alexloas
Novice

Oct 31, 2009, 4:00 PM

Post #1 of 4 (539 views)
addition in subroutines Can't Post

Hey I'm having some trouble in order to calculate the average for a subroutine.
Any ideas?

sub Average {
my @list = @_;
my $sum = #not sure how to define $sum, I just want to add all the numbers in this variable
my $average = ($sum/@list);

return $average;
}


Pravin27
New User

Oct 31, 2009, 11:27 PM

Post #2 of 4 (528 views)
Re: [alexloas] addition in subroutines [In reply to] Can't Post

Hi ,

Try this....

You can pass ref array to function Average()


Code
 sub Average { 
my $list = shift ;
$sum += $_ while (<@$list>);
my $average = ($sum/@$list);
return $average;
}



7stud
Enthusiast

Nov 1, 2009, 2:05 AM

Post #3 of 4 (516 views)
Re: [alexloas] addition in subroutines [In reply to] Can't Post

You could do this:


Code
use strict; 
use warnings;

$\ = "\n";

sub Average {
my $sum = 0;

foreach my $num (@_) {
$sum += $num;
}

return $sum/@_;
}

print Average(1, 2, 3);

--output:--
2



toolic
User

Nov 1, 2009, 12:59 PM

Post #4 of 4 (505 views)
Re: [alexloas] addition in subroutines [In reply to] Can't Post

Another idea is to use the sum function from the Core List::Util module:


Code
use strict;    
use warnings;
use List::Util qw(sum);

sub avg {
return sum(@_)/@_;
}


 
 


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

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