Make like a Banana and .split()
Of the many recurring ColdFusion related questions, one of the most prevalent is one that has to do with the fact that ColdFusion ignores empty elements in a list.
This came up (again) today on the CF-Talk mailing list, which in and of itself is not news… but today I saw an answer that I’ve not seen before, and I like it a lot. Usually the answer that I see is to replace consecutive delimiters (,, for example) with a space between those delimiters (such as , ,). Of course, this is somewhat hokey as it will only work for 2 consecutive delimiters and not 3 (or 4 or 5 or…). There are regex solutions, but i think a number of ColdFusion developers tend to give regex a wide berth when possible.
Peter Boughton offered up 3 different possible solutions, one of which I _really_ like. Java has a split() method. The split() method takes a list and creates an array based on the list delimiter. It’s really very similar to ColdFusion’s own listToArray() function, except listToArray() will (as noted) ignore empty list elements. So a list of 1,2,3,,5 will yield a 4 element array using listToArray().
However, split() will create a 5 element array (with element number 4 being an empty string, as you’d often hope/expect). As with other native Java string methods, you can use this to your heart’s content within ColdFusion.
So consider the following:
<cfset myList = "1,2,3,,5" /> <cfset myArray1 = listToArray(myList) /> <cfset myArray2 = myList.split(',') /> <cfdump var="#myArray1#" label="Array1" /> <cfdump var="#myArray2#" label="Array2" />
The first array which used the built in ColdFusion function doesn’t give a true representation of the list. However, the second array, which uses the Java split() method, does. Very, very cool.
However… I did a little bit of googling and came across a blog entry by the inimitable Ben Nadel that mentions a very interesting "gotcha" regarding using the split() method. The array that is created is -not- a regular ColdFusion array (even though the dump looks just like one). You can read it (i.e. use an arrayLen() method on it to get the length), but you can’t modify it. You can’t modify any of its elements, you can’t add an element, or remove an element.
So… very cool as far as dealing with the empty list element in ColdFusion. Not (necessarily) very cool (or useful) beyond that (depending on your needs).
On a somewhat related note… Rupesh Kumar (an engineer on the ColdFusion team) blogged about some of the native Java array methods that can be used in ColdFusion. Definitely worth a read (and a bookmark).6 comments | 4,072 views