0

Im following a perl book, and one exercise has you enter a number, sum them up until you type 999(the exit code). Their example works, but when I try using use strict, I cant figure out how to get the variable in the while loop to go global

Here's what I tried:

#!/usr/bin/perl -w
use strict;
my $n = 0;

while ($n != 999) {
    my $sum += $n;
    print "Enter a number, 999 to stop: ";
    $n = <STDIN>;
}

print "the sum is ", $sum;

Ive read its best to use strict in code, so its why im asking.

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by ryan461
1

You have to define the variable in scope outside the loop. By using "my" inside, it loses scope outside.

#!/usr/bin/perl -w
use strict;
my $n = 0;
my $sum=0;
while ($n != 999) {
    $sum += $n;
    print "Enter a number, 999 to stop: ";
    $n = <STDIN>;
}
 
print "the sum is ", $sum;
0

You have to define the variable in scope outside the loop. By using "my" inside, it loses scope outside.

#!/usr/bin/perl -w
use strict;
my $n = 0;
my $sum=0;
while ($n != 999) {
    $sum += $n;
    print "Enter a number, 999 to stop: ";
    $n = <STDIN>;
}
 
print "the sum is ", $sum;

Thanks :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.