It has to do with the special way that foreach works. In the statement foreach $n (1, 2, 3) {}, $n actually becomes the value in the LIST on each interation of the loop. It doesn't just get a copy of it in the variable $n. So in your example, $n would actually contain the read-only value 1 on the first iteration of the loop.
So what would happen if after the loop you tried to assign a value to $n? If it was not localized in the foreach loop, then you would be trying to assign a value to a read-only value, and you would get an error.
my $n; foreach $n ( 1, 2, 3 ) { } $n = 'foo';
If $n was not localized, you would get a "Modification of a read-only value attempted ..." error in your code.
A better explaination of this issue can be found here in the perl5-porters archive.
- Cees
In reply to Re: Re: for loop localisation bug?
by cees
in thread for loop localisation bug?
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |