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

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner:


New User

Sep 21, 2012, 3:47 PM

Post #1 of 4 (2464 views)
Array Can't Post

Hey guys I am taking an intro to scripting languages and we are using perl but I seem to be stuck in this problem.

"Find the average of the numbers in an array (@nums) of unknown length.

I know it starts something like this

@nums = ();

But I don't know where to go from there.

New User

Sep 21, 2012, 9:25 PM

Post #2 of 4 (2456 views)
Re: [perlguru22] Array [In reply to] Can't Post


@nums = ();
$sum += $_;
$size = @nums;
$average = $sum / $size;
print "$average";

Would this be the correct way to do it


Sep 22, 2012, 7:13 AM

Post #3 of 4 (2448 views)
Re: [perlguru22] Array [In reply to] Can't Post

That is a good way to do it without using modules, but I do strongly recommend 'use strict' and 'use warnings' in all perl programs.

Refer to the sum function in the module List::Util to avoid reinventing the wheel.
Good Luck,

Veteran / Moderator

Sep 23, 2012, 8:22 PM

Post #4 of 4 (2435 views)
Re: [perlguru22] Array [In reply to] Can't Post

Your overall algorithm looks correct, except that your array is declared as follows:

@nums = ();

meaning that it will be empty. Calculating the average (or mean, or median, or variance, or standard deviation, etc.) on zero value is not very interesting.

You need to find a way to populate @nums with meaningful values. Maybe you could use the rand function or, at worse, hard code some values.


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

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