CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Uncomprehensive while-loop with undef variable: Edit Log



Wildcard
Novice

Apr 23, 2017, 6:09 AM


Views: 1305
Uncomprehensive while-loop with undef variable

hello there, I just learn recently Perl, so I experimented a bit around, and this ist what i don't get:

I started with

Code
$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:

Code
$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)


Edit Log:
Post edited by Wildcard (Novice) on Apr 23, 2017, 6:26 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives