Coyote's Guide to IDL Programming

Extracting a Field from a Structure

QUESTION: Darran Edmundson in Australia asks this question:

Consider the following:

   struct = {name: 'john', age:18}
   field = 'age'

Given the string field, is there an easy way to extract the value of the corresponding structure tag in struct? The string field is not known ahead of time.

ANSWER: The function Tag_Names can be used to return the fields of a structure to you. The string array that is returned has the field names in uppercase characters. The Where function can be used to get an index into that string array where the field name is the same as the field you are looking for, field in this case.

The trick in this answer is knowing that you can use that index to extract the value of that field. In the structure dereferencing, the tag index must be inside of parentheses. The final answer looks like this:

   struct = {name: 'john', age:18}
   field = 'age'
   index = Where(Tag_Names(struct) EQ StrUpCase(field), count)
   IF count NE 0 THEN Print, struct.(index[0]) ELSE Print, 'Field not found.'

Web Coyote's Guide to IDL Programming