Wildcard
Novice
Apr 23, 2017, 6:09 AM
Post #1 of 2
(1228 views)

Uncomprehensive whileloop with undef variable

Can't Post


hello there, I just learn recently Perl, so I experimented a bit around, and this ist what i don't get: I started with
$n = 1; while ($n<10) { $sum += $n; $n += 2; } print "result is $sum \n " ; This is fairly simple, it goes from loop 1 (n = 1) to loop 5 (n = 9) and adds them to 1+3+5+7+9, which gives 25. Now I tried the following:
$n = 1; while ($sum<10) { $sum += $n; $n += 2; } print "result is $sum \n " ; Now the result is supposed to be 16, and I dont understand it frankly.. the numbers n ought to sum up to the $sum until it reaches 10. So what actually happens is: 1+3+5+7 = 16 but this is an error statement or did I miss something? when I say print "result is $n \n" then it gives the expected result 9. I just wonder how the perl compiler handles the $sum or why it gives me 16, I hope you understand an can help me here :) The point is, I didn't declare the variables (my $n ; my $sum) to see how the program behaves.. is this the source of all problems?
(This post was edited by Wildcard on Apr 23, 2017, 6:26 AM)
