As a follow up to my earlier post, another common 'gotcha' with ColdFusion Lists are empty list items. What's an empty list item? Consider this simple list of names:
<cfset names="Baltar,Apollo,Starbuck,,Bozo">
I think most people, including myself, would look at that and say that the list had 5 items, with the 4th item being a simple empty string. But ColdFusion simply ignores empty list items. If you perform a listLen() on that string, you get 4.
Now - we can argue about whether or not that makes sense. I'm not quite sure it does - but that's how ColdFusion handles it. If you want to handle this differently, you need to write your own code, or perhaps replace the empty items with a string that will represent 'null' for your application. Check out ListFix() at CFLib.org for a UDF that does this.
Thanks to Phillip Senn for reminding me of this - I actually forgot it during my presentation.
More Variable Type Gotchas tomorrow - after I arrive at cf.Objective!
Archived Comments
Well I kind of agree. The thing is that a lot of old school programming languages had functions to compress simple lists and arrays so that you'd have the best of both worlds. If you wanted to leave the empties alone find - don't do anything and loop through them, but if you wanted to eradicate them then CompressArray away you went, but like all good things this came at a speed cost.
In my humble opinion there is a reason for everything. For instance look at Lists in C++, for those of you who aren't familiar they're just sequences of elements stored in a linked list. And compared to Vectors they are waaaay fast for insertions and deletions - but they're slow slow slow for random access activities. This came to mind when I read your post because if speed is what you need, and every web app does, then it is natural to ignore empty list elements at a the system level. This is what makes all of ColdFusion's deadly fast and wickedly cool list functions so blindingly fast, well I think that they're cool and fast but I'm sure somebody is reading this calling me an idiot. Anyway, just digital food for thought.
Yeah . . . got bitten by this at least once in the past.
For cases like this I always use the Java split() function. Sure it will result in an Array instead of a List, but does it really matter?
So to get a length of the List in your example I would do: ArrayLen(names.split(","))