Christopher Smith on 24 Nov 2003 23:19:07 -0000 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
[ALACPP] How Perl sucks even worse than C++ when it comes to assoc arrays |
So, more than a few times at meetings we've talked about how map's can be used as assoc arrays, and how evil the implementation is. In particular, in order to allow adding any entry by: myMap[myKey] = myValue; in the case where there was no prior entry for myKey, operator[] is a non-const method which will actually add an entry to the map if myKey is not already in there. There is no easy way to solve this in C++ without adding a level of indirection. myMap[myKey] could return some special iterator that creates an entry when operator=() is invoked (it would also need to implement operator V in order to do conversion), but then things like: myMap[myKey].aMethod(arg1, arg2); would probably not work too well. Of course, I thought to myself, this problem can all be solved nicely using a language where assoc arrays are built in to the language. This made me think of Perl. In Perl doing: $foo{'bar'}; does not create an entry in %foo with a key of 'bar'. However: $foo{'bar'} = 'baz'; will. All magical and wonderful right? Well, I discovered this one the other day: if (defined($foo{'bar'}->{'baz'})) { #some stuff } I was working with a hash who's values were references to hashes. I figured that one of two things would happen in the event that %foo doesn't contain 'bar': a) A runtime error occurs, b) Perl magically returns undef from the hash lookups and everything works great. What I missed was option 'c': Perl will insert a bogus entry in %foo, and then evaluate ->{'baz'} in that context (returning an undef). This generates no problems under the auspices of 'strict' and 'warnings'. So, the next time you think that C++'s approach to the problem is dangerous and error prone, take a close look at Perl. ;-) -- Christopher Smith <x@xxxxxxxx> _______________________________________________ alacpp mailing list alacpp@xxxxxxxxxxx http://lists.ellipsis.cx/mailman/listinfo/alacpp