There are situations where it may be useful to create variables at runtime in an IDL program, taking the variable names from a string array. Though there are a couple ways of doing this, I’d like to use SCOPE_VARFETCH here, elaborating on an example found on its Help page.
I want to read, into individual variables, the data from all the PNG files in IDL’s examples/data directory (even though there are better ways to do this in IDL 8; e.g., with a list). Here’s how I can get the paths to these files:
IDL> start_dir = filepath('', subdirectory=['examples','data']) IDL> ext = '.png' IDL> png_files = file_search(start_dir, '*'+ext)
I intend to make an eponymous variable from the base name of each file:
IDL> varnames = file_basename(png_files, ext) ; a string array IDL> print, varnames africavlc afrpolitsm avhrr mineral moon_landing rockland shifted_endocell
Now loop through the files, reading them with READ_PNG into (here’s the trick) named variables created using SCOPE_VARFETCH:
IDL> for i=0, n_elements(png_files)-1 do $ > (scope_varfetch(varnames[i], /enter, level=1)) = read_png(png_files[i])
Note the use of enclosing parentheses to group the output from the SCOPE_VARFETCH function. This is a legal, but uncommon, syntax in IDL (and may be worth its own blog post). I’m also choosing not to read the color tables from the files that have them.
Examine the results:
IDL> help, names='*' AFRICAVLC BYTE = Array[540, 560] AFRPOLITSM BYTE = Array[600, 600] AVHRR BYTE = Array[720, 360] EXT STRING = '.png' I INT = 7 MINERAL BYTE = Array[288, 216] MOON_LANDING BYTE = Array[300, 300] PNG_FILES STRING = Array ROCKLAND BYTE = Array[3, 320, 461] SHIFTED_ENDOCELL BYTE = Array[615, 416] START_DIR STRING = '/usr/local/exelis/idl82/examples/data/' VARNAMES STRING = Array