On Sat, Jul 9, 2011 at 1:33 AM, J. S. John <phillyj...@gmail.com> wrote:
> Hi all, > I'm teaching myself perl. Right now, I am stuck with this script. I > don't understand how it works. I know what it does and how to do it by > hand. > > $n = 1; > while ($n < 10) { > $sum += $n; > $n += 2; > } > print "The sum is $sum.\n" > > I know $sum is initially 0 (undef). I see that $sum becomes 1, then $n > becomes 3. The loop goes back and then I don't understand. Now $sum is > 1+3? > > Thanks, > JJ > > -- > To unsubscribe, e-mail: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ > > > First of all it is a really bad thing to not use warnings and strict in your scripts just start your script with: use warnings; use strict; and this script will end up screaming that you have to declare your variables. So your script would end up looking like this: use warnings; use strict; my $n = 1; my $sum; # Should actually be my $sum = 0; even if it is only for readability but we shall let that slide for now ;-) while ($n < 10) { $sum += $n; $n += 2; } print "The sum is $sum.\n" So what does the script do? Well literally it says while $n is smaller then 10 execute what is in side the { } brackets. Inside you say $sum = $sum + $n; and then $n = $n + 2; So on the second loop you look at the value of $n which now is 1 + 2 = 3. So then we take $sum which is 1 and add $n to that so 1 + 3 = 4 and we increase $n by 2 ending up at 5. The next loop (5 is smaller then 10 after all) $sum becomes 4 + 5 = 9 and $n becomes 5 + 2 = 7 The next loop (7 is smaller then 10 after all) $sum becomes 9 + 7 = 16 and $n becomes 7 + 2 = 9 The next loop (9 is smaller then 10 after all) $sum becomes 16 + 9 = 25 and $n becomes 9 + 2 = 11 Then 11 is not smaller then 10 anymore an the loop ends the next thing you do is print the value of $sum which should by now be 25. To see if I am right why not modify the script a little so it will print the inner values: use warnings; use strict; my $n = 1; my $sum = 0; while ($n < 10) { print '$sum = ' . $sum . ' $n = ' . $n; print '$sum += $n'; $sum += $n; print '$sum = ' . $sum; $n += 2; print '$n + 2 = ' . $n; } print "The sum is $sum.\n" Now it should show you exactly what it is doing inside the loop :-) Regards, Rob