Example: Reading Formatted Table Data

IDL explicitly formatted input/output has the power and flexibility to handle almost any kind of formatted data. A common use of explicitly formatted input/output involves reading and writing tables of data. Consider a data file containing employee data records. Each employee has a name (String, 32 columns) and the number of years they have been employed (Integer, 3 columns) on the first line. The next two lines contain each employee's monthly salary for the last twelve months. A sample file named employee.dat with this format might look like the following:

Bullwinkle                       10 
1000.0    9000.97   1100.0                        2000.0 
5000.0    3000.0    1000.12   3500.0    6000.0     900.0 
Boris                           11 
400.0     500.0    1300.10    350.0     745.0    3000.0 
200.0     100.0     100.0      50.0      60.0       0.25 
Natasha                          10 
950.0    1050.0    1350.0     410.0     797.0     200.36 
2600.0    2000.0    1500.0    2000.0    1000.0     400.0 
Rocky                            11 
1000.0    9000.0    1100.0       0.0       0.0    2000.37 
5000.0    3000.0    1000.01   3500.0    6000.0     900.12 

The following IDL statements read data with the above format and produce a summary of the contents of the file:

;Open data file for input. 
OPENR, 1, 'employee.dat' 
 
;Create variables to hold the name, number of years, and monthly  
;salary.  
name = '' & years = 0 & salary = FLTARR(12) 
 
;Output a heading for the summary.  
PRINT, FORMAT='("Name", 28X, "Years", 4X, "Yearly Salary")' 
 
;Note: The actual dashed line is longer than is shown here. 
PRINT, '========' 
 
;Loop over each employee.  
WHILE (~ EOF(1)) DO BEGIN 
 
   ;Read the data on the next employee. 
   READF, 1, $ 
   FORMAT = '(A32,I3,2(/,6F10.2))', name, years, salary 
 
;Output the employee information. Use TOTAL to sum the monthly  
;salaries to get the yearly salary. 
   PRINT, FORMAT='(A32,I5,5X,F10.2)', name, years, TOTAL(salary) 
 
ENDWHILE 
 
CLOSE, 1 

The output from executing these statements on employee.dat is as follows:

Name                         Years    Yearly Salary 
====================================================== 
Bullwinkle                      10       32501.09 
Boris                           11        6805.35 
Natasha                         10       14257.36 
Rocky                           11       32500.50