PDA

View Full Version : Newbie help


CarlosSanchez
11-12-2002, 07:21 PM
I'm a newbie trying to learn perl, and trying to just learn from a book. I'm kinda stuck on this problem, and wanted to ask anyone to see how I might do this:

How can I write a simple program which gets input from the user as a series of numbers (checks to make sure the input is all numbers, including negative numbers, and with only 1 decimal). Then pass that set of numbers into 3 subroutines, each of which calculate a value and return it. This first sub should calculate the average of the numbers, the second should calculate the highest value in the list, and the 3rd should calculate the total of values.

Help?

Mouldy_Goat
11-14-2002, 12:20 AM
Hi,

I knocked up a little script that did what you described, and uploaded it here (http://www.mouldygoat.34sp.com/public/numbers.pl.txt).

I didn't think you'd like it very much if someone just posted an answer up already, hence why I've given you a link to the script if you want to see it.

This is the way in which I did things (my algorithms).
I made four subroutines to handle the tasks:
validate(), total(), average() and highest().
total() works by just adding each of the values passed to it to a running total and then returning that.

average() works by working out the total() of it's arguments and then dividing by the number of arguments passed to it. (Although it raises an exception if no arguments are passed, since this would result in a division by zero).

highest() works by going through all of the arguments passed to it, and assigning the current variable being looked at to $highest if the current variable is higher than $highest.

validate() is a little more complicated the way I did it. Here, I just used a single regular expression (pattern match) to check whether the input is valid.

This is what it looks like:
/^[+-]?(?:\d*\.?\d+|\d+\.?\d*)(?:[eE][+-]?\d{1,2})?$/

The way my pattern match works is like this:
1) At the start of the input, a plus or a minus is allowed, although not required.
2) After this, there must be either a) none or more digits, which may be followed by a decimal point which must have one or more digits after this or b) one or more digits, which may be followed by a decimal point which can have none or more digits after it.
3) After this, the user can have a small or capital letter 'e', which may in turn be followed by a plus or minus, which must then be followed by one or two digits. (This just allows for exponential form to be written.

I'm not entirely sure that this pattern match is bulletproof - but I'm fairly confident in it.

Hope that helps a bit.

CarlosSanchez
11-14-2002, 08:59 AM
Moudly - I could not see the link for some reason. Can you repost? Thanks

Mouldy_Goat
11-14-2002, 05:56 PM
Sorry, my mistake, try this instead:
http://www.mouldygoat.34sp.com/public/numbers.txt