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

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

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



Apr 23, 2017, 6:09 AM

Post #1 of 2 (1499 views)
Uncomprehensive while-loop 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)


Apr 23, 2017, 10:53 AM

Post #2 of 2 (1486 views)
Re: [Wildcard] Uncomprehensive while-loop with undef variable [In reply to] Can't Post

After the third loop $sum has the value 9. The 9 is less than 10, so the loop runs again (it adds 7 to the 9 and gets 16). The 16 is not less than 10 so the while loop terminates. You then print the current value of $sum (16).

Perhaps the easiest way to do what you want is:

use strict;
use warnings;
my $sum =0;
my $n = 1;
while (($sum + $n)<10)
{ $sum += $n;
$n += 2;
print "result is $sum \n " ;

result is 9

I recommend that you always use strict and warnings. Although they would not have helped in this case, they do catch many common mistakes.
Good Luck,


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

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