Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Re: Re: •Re: "for" surprise

by fletcher_the_dog (Friar)
on Nov 21, 2003 at 20:26 UTC ( #309039=note: print w/replies, xml ) Need Help??


in reply to Re: Re: •Re: "for" surprise
in thread "for" surprise

That way, $i can't be used outside the loop, and I consider that a goo +d thing.
I agree that makes sense and I do it myself all the time, but sometimes it might not be what you want to do and it might not be good thing in which case even if you think you are changing the behavior, you are not.
But why are you using a loop over a fixed range instead of a loop from + 1 to $end anyway?
It was a small example not real code. Where it says "# do some useful stuff" there would be ... some useful stuff :-)

Replies are listed 'Best First'.
Re: Re: Re: Re: •Re: "for" surprise
by etcshadow (Priest) on Nov 22, 2003 at 03:42 UTC
    ...or, for that matter, why we have:
    for ($i=0; $i<53; $i++) { }
    loops, as well. Even though perl's list-iterating for-loops are incredibly sweet, and replace 99% of for-loops written in other languages, there's still that 1% of iterating loops that aren't list-iterating loops... and that's why perl still has for( ; ; ) loops as well.

    The real reason why the value is localized within the loop is that it is not the variable (by the same name) outside of the loop. Period. What it is, though, is an alias to the item in the list being iterated over. That is why you can do things like:

    foreach my $item (@list) { $item = mutate $item; }
    and it produces the same result as:
    @list = map { mutate $_ } @list;
    That is... in the nth iteration of the loop, the list-iterator variable IS the nth item in the array. They are one and the same.

    With that context in mind, ask yourself how much sense it would make that your list iterator variable was not localized.


    ------------
    :Wq
    Not an editor command: Wq
Re: "for" surprise
by Abigail-II (Bishop) on Nov 21, 2003 at 21:24 UTC
    but sometimes it might not be what you want to do
    That's why we have a while as well.

    Abigail

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2021-09-18 17:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?