""J. S. John"" wrote in message news:caahf0rkhyip680xk9kz+3q4uvw79s2dh8denulob_2gxlyf...@mail.gmail.com...

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

Hello JJ,

It is sometimes helpful to put print statements in a routine to follow the flow of action. However, if you don't have Perl installed that would be a problem :-)

$sum += $n;

This statement is shorthand for $sum = $sum + $n;
Whatever value (0 the first time through the loop) is in $sum is added to the value of $n, (which starts at 1 and increases by 2 for every time though the loop: $n = $n + 2), and stored in $sum.

In effect, this loop is calculating the sum of odd integers from 1 to 9.

Here it is with some print (say) statements:

#!/usr/bin/perl
use strict;
use warnings;
use 5.014;

my $n = 1;
my $sum;
while ($n < 10) {
   say "n: ", $n;
   say "sum: ", $sum += $n;
   $n += 2;
}

And it prints:
n: 1
sum: 1
n: 3
sum: 4
n: 5
sum: 9
n: 7
sum: 16
n: 9
sum: 25

The loop ends because $n gets incremented to 11 and fails the loop test ($n < 10).

Hope this helps explain it for you.

Chris

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to