in reply to Re: for loop localisation bug?
in thread for loop localisation bug?

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

Replies are listed 'Best First'.
Re: Re: Re: for loop localisation bug?
by demerphq (Chancellor) on Dec 29, 2003 at 19:07 UTC

    Just to add a term: the name for this kind of behaviour is aliasing. Which is a concept that people seem to have little trouble using in practice, but much harder to understand and explain. Some languages have no concept of aliasing at all. In perl @_ is aliased, as are the iterator in a foreach loop, grep, map and sort. In Pascal "var" parameters are essentially aliases, as are normal parameters in VB (byref parameters). Its my understanding that C has no aliases.

    I find a useful way of thinking about aliases is that they are like references that need not be dereferenced.


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi