in reply to New Perl user - help with my homework

Welcome to Perl and the Monastery, Eardrum!

Thank you for letting us know this is homework. We're happy to help, if you're willing to learn and show your efforts - the latter you've done by posting your code so far, thank you for that. Also take Corion's suggestions into account - for example, the other homework problems don't really have anything to do with this first question, you might consider removing them, or at least placing them inside <readmore>...</readmore> tags. See also How do I post a question effectively? and How do I change/delete my post?.

First, a couple of comments on your code:

As for your task, I found the problem statement "the average number from 1 to the number that the user inputs (in jumps of 2)" a little unclear, but the example (1+3+5)/3 = 3 helps. In this case, I think it helps to work out the steps "on paper":

  1. The first step is to get all the numbers from 1 to 6 in steps of two. To see what your loop is doing, try putting a print statement at the top of the loop, such as print "i=$i\n"; - see also the tips on the Basic debugging checklist.

  2. The next thing to do is sum up all of these numbers. You've got a variable $sum, which you're starting out at 1 and incrementing by 2 in the loop. I suggest you think about this as the main point: how could you use this variable to sum up the numbers from the previous step? Try adding another print statement or two to show how $sum changes.

  3. Finally, you'll want to divide by the count of numbers that you summed up. In your code, you're pushing the string '1' into an @array and then using scalar(@array) to get the number of elements in the array after the loop. Although this works, consider what happens when $limit is a large number, such as in the millions or more: @array will contain a lot of elements. There's a more efficient way to count the number of times the loop runs - I'm sure you can come up with an idea :-)

A side note: you're using what's usually known as the C-style for loop. This is fine for cases like this one, where you need to count up by something other than one. For cases where you need to count up by ones, Perl offers another, nicer-looking mechanism which has the advantage of being less error prone (less chances for typos and off-by-one errors): the foreach loop (which can also be written for), and the Range Operators. The following prints all the numbers from 1 to 10:

for my $i (1..10) { print "i=$i\n"; }

(In Perl, There Is More Than One Way To Do It, so there are ways to count up by two's in this example too, but let's leave that for another time :-) )