It's due to the way closures are currently impelemented.
Internally, sub 'test' has its own lexical $foo which just
happens to be an alias to to the $foo in the main file (technically each CV has its own scrachpad, each with a pointer to the same SV).
Within the for loop, the main $foo is now aliased to something
else (technically the pointer for $foo in main's pad temporarily points elsewhere), so the two $foo's are now different.
I haven't been able to think of a way of fixing this that
isn't inefficient, otherwise I would probably have done it by now.
Dave.