Fortran: Namelists
Formatted I/O in Fortran 95 can be difficult to understand and easy to break. One alternative is the use of namelists which allow the association of names with values.
Syntax
Each namelist in the source must be declared. This is achieved with the NAMELIST statement which takes the name of the namelist in slashes as the first argument and the comma-separated list of variables following that. The variable names must also be declared independently.
Within the data file (for reading), each namelist begins with an ampersand (&) or dollar ($) followed immediately by the name of the namelist and then whitespace. This is followed by a sequence of name=list pairs (where the list is a list of constants) separated by commas. Any new line started within the namelist must begin with whitespace. Inline comments using the exclamation mark (!) are allowed. Finally, the namelist is ended with / or &END or $END.
To read or write, the relevant statement must include the option NML=namelist.
Examples
PROGRAM nltest
IMPLICIT NONE
INTEGER :: iarr(3), j
REAL :: ascalar
CHARACTER (LEN=11) :: label
NAMELIST /qt/ ascalar, iarr, label
! Set some values
iarr = (/-16, 144, 0/)
j = 255
ascalar = 3.1415926535
label = 'Hello world'
PRINT 100, iarr, j, ascalar, label
OPEN (UNIT=10, FILE='nltest.dat', STATUS='UNKNOWN')
WRITE (10, NML=qt)
CLOSE (10)
PRINT 100, iarr, j, ascalar, label
! Change the values
iarr = (/3457389, -1, -9999/)
j = 111
ascalar = 5e-12
label = 'Hello there'
PRINT 100, iarr, j, ascalar, label
OPEN (UNIT=10, FILE='nltest.dat', STATUS='OLD')
READ (10, NML=qt)
CLOSE (10)
PRINT 100, iarr, j, ascalar, label
100 FORMAT (' iarr = ', 3I7, ' j = ', I3, &
' ascalar = ', E12.4, ' l = ', A)
END PROGRAM nltest
This example shows the syntax and use of namelists for both writing and reading. Four variables are declared, including one array, but only three of these are assigned to the namelist qt which is used for file-based I/O. The program displays the contents of the variables after first setting the values and then after writing to the file, changing the values in the program and finally after reading the namelist back in from the file.
When to use namelists
Only sequential files should be used with namelists. They may be useful when there is a common large set of data serving as input for a number of different programs, each of which will only require a small subset of the data.
When not to use namelists
Namelists should not be used with direct-access files. They will not be useful when the symbol names in the programs are unknown or likely to change.