Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Variable scope in while loop

by Athanasius (Chancellor)
on Dec 20, 2012 at 02:37 UTC ( #1009671=note: print w/replies, xml ) Need Help??

in reply to Variable scope in while loop

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 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,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1009671]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (1)
As of 2017-12-16 19:41 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (458 votes). Check out past polls.