Returning the Right Length
A well known function in SAS is the LENGTH function – used to return the length of a character string.
The syntax for this function is:
result = LENGTH (character string)
The function will return an integer which represents the position of the last (on the right) character in the string. Trailing blanks will be ignored.
However, there are two points to note about this function.
Firstly, if the function is used with a numeric constant or variable, then SAS will convert it to a right-justified character string, using the BEST12. format. This means that the LENGTH function will automatically return the value 12. It will also write a note to the SAS log, saying that numeric values have been converted to character values, which is something which should always be avoided - you should want to be in control of when numeric values are converted to character, and not leave this to SAS.
The second point to note is that what is returned when the character string is missing may not be what is expected. The result returned by the following:
result = LENGTH('')
This may not be what you want, and if not accounted for may lead to unexpected results later on.
It is therefore recommended to use the SAS9.2 function LENGTHN. This function behaves in the exact same way as the LENGTH function, with the exception that the following:
result = LENGTHN('')
will return the value 0.