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

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
You best off keeping $var in the scope of the loop:
for my $var (0..9){ #UPDATE: I changed 1-9 to 0-9 print $var; } #actually, this is better . . . but I digress . . . print (0..9);
No need to declare $var and assign zero to it like you did in the first example. There really is no need to keep $var around after you have finished the loop. If you need to remember what it was, look at the array you were looping through. Rarely are you going to say (1..9) in any serious program, unless you love playing catch-up to scalability:
my @numbers = (0..9); foreach my $n (@numbers) { print $n; } print "\n", scalar(@numbers), "\n";
will produce
0123456789 10
As for why this:
my $var; for ($var=1; $var < 10; ++$var){ print $var; } print "\n", $var, "\n";
yields $var = 10 after it finishes, the reason is because that's how a C-style for loop works. Think about it. It _HAS_ to be 10, because $var increments 1 at a time . . .
and in order for the loop to stop . . . .
$var has to be equal to 10 . . . ;)

Jeff

R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
L-L--L-L--L-L--L-L--L-L--L-L--L-L--

In reply to (jeffa) Re: (s)coping with foreach by jeffa
in thread (s)coping with foreach by greenFox

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2024-04-20 15:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found