Hello euswdwj, and welcome to the Monastery!
In the case where the scope of the loop variable does not need to extend beyond the loop itself, a C-style for loop may be preferable to the more usual while:
#! perl use Modern::Perl; my $number = 7; print "Before the loop, \$number is $number\n\n"; for (my $number = 0; $number != 10;) { print 'Please enter a number (10 to quit): '; chomp($number = <STDIN>); print "You entered: $number\n"; } print "\nAfter the loop, \$number is $number\n";
Sample run:
12:34 >perl 438_SoPW.pl Before the loop, $number is 7 Please enter a number (10 to quit): 1 You entered: 1 Please enter a number (10 to quit): 0 You entered: 0 Please enter a number (10 to quit): 100 You entered: 100 Please enter a number (10 to quit): 10 You entered: 10 After the loop, $number is 7 12:35 >
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: Variable scope in while loop
by Athanasius
in thread Variable scope in while loop
by euswdwj
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |