Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Variable scope in while loop

by Athanasius (Monsignor)
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 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,


Comment on Re: Variable scope in while loop
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1009671]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2014-12-26 11:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (171 votes), past polls