| They weren't originally intended to provide namespacing, as far as I know. They were there to make the compiler's life easier. The reason that an array subscript is "$foo[0]" is because the $ sigil means "HEY COMPILER, the expression here is going to evaluate to some scalar". @foo is the entire list and the compiler treats it as a list type; $foo[0] is an element of the list and needs storage/behavior of a scalar. Same thing for hashes: %bar is the whole hash; $bar{quux} is an element and must be treated by the compiler as a scalar. The programmer must remember that square braces mean array subscript and curly braces mean hash lookup. So basically, this is a compiler optimization implemented by having the programmer provide hints to the compiler. It's overhead that probably isn't needed in the modern age, but we're effectively stuck with it. It wouldn't be so bad if they hadn't made the second (and IMO worse) decision: You can reuse symbols across contexts. The way this works is that the compiler maintains a symbol table where each symbol has a slot available for each of the types (scalar $, array @, hash %, subroutine &). This was originally the way to emulate pass-by-reference: you'd write a subroutine that assigned its arguments into typeglobs (* foo — think of it as a wildcard for all things named foo that behaves as a magic scalar with the contents of foo's symbol table entry) and then pulled them back out as the types it wanted: local(*foo) = @_;
foreach $bar (@foo) {
do_something($bar);
}
This amounts to telling the compiler "I want to alias the name foo in all contexts to my argument, and then go look at what's stored in the array at that name" and is a poor man's pass-by-reference.Perl 5 has a real reference system that completely obviates the need for this, except for the case of monkey-patching a subroutine, where you still say: local *Package::quux = sub { ... }"
What's left is an unfortunate case where things like the GP mentioned ($bar = $foo[$foo]) are possible, and people who think they're being clever will do these things. Like the parent said, this is not a good thing to do. |
I'm not entirely sure that's correct. I think Larry Wall (being a linguist originally) designed it that way because he thought that using context-sensitive sigils was more like regular speech where leading words indicate the number, i.e. 'a cup' vs. 'some cups'...