Vectorizing the STRMID Function

QUESTION: Isn't it odd that STRMID can't operate on a string array? I can get a nice set of positions from an array with STRPOS, but can't apply them like this:

    if (file_info(filename)).exists then begin
    endif else return,0

I might as well get the positions one at a time, too. Sigh...

ANSWER: The answer is provided in an October 11, 2006 IDL newsgroup article by Wayne Landsman, who quotes himself in this long (and somewhat humorous) long-ago thread in the IDL newsgroup. As it happens, STRMID does operate on string arrays, but with a funky syntax. Here is Mr. Landsman...

The problem when STRMID was vectorized for IDL 5.3 was that it was made too powerful -- it handles simultaneously both extraction from multiple strings and multiple extractions from a single string. In practice, I think the first situation -- extraction from multiple strings -- is far more common, but has an ugly syntax in the current STRMID implementation.

The online help describes the vector use of STRMID this way:

"If First_Character or Length is an array, the size of their first dimension determines how many substrings are extracted from each element of Expression. We call this the "stride". If both are arrays, they must have the same stride. If First_Character or Length do not contain enough elements to process Expression, STRMID automatically loops back to the beginning as necessary. Excess values are ignored. If the stride is 1, the result will have the same structure and number of elements as Expression. If it is greater than 1, the result will have an additional dimension, with the new first dimension having the same size as the stride. "

In your example, assuming the number of values in your array is npts, the call to STRMID needs to be as follows:

   strmid(lbl, 0, reform(p-1, 1, npts))

I've thought about writing a wrapper to STRMID that provides an easy syntax for the common case of single extractions from multiple strings, but in practice I usually use the IDL Astronomy routine GETTOK to extract strings. (This includes an internal vector call to STRMID.)

The person who asked this question originally swears he read that IDL documentation paragraph three times before he decided whatever it meant didn't apply to him. And he read it five more times after he learned it did apply to him before he had a clue what it meant. When the light finally went off, he realized he could also write the command above as this, which made a lot more sense to him.

   strmid(lbl, 0, transpose(p-1))

Web Coyote's Guide to IDL Programming