Enter Home Page

Exploring NAMELIST

(in progress)

The NAMELIST features of Fortran 2003/2008 have a number of sometimes surprising uses such as reading command line arguments, processing configuration files, easily creating problem sets from input files, and even providing for interactive input.

Fortran 2003 NAMELIST-based command line argument parsing

Pre-Fortran 2003 compilers often support the f2003 features required to use NAMELIST to create a unprecedentedly simple method of passing values via the command line. With a f2003-compliant compiler the following example program simply needs an initialized variable added to the NAMELIST and it automatically is available as a command line argument (assuming your version of GET_COMMAND(3f) does not return the command name itself, which the standard optionally allows):

PROGRAM testit
   CHARACTER(LEN=:),ALLOCATABLE :: string  ! stores command line argument
   CHARACTER(LEN=255) :: message           ! use for I/O error messages
   !---------------------------------------------------------------------------
                                           ! declare and initialize a NAMELIST
   INTEGER    :: i=1, j=2, k=3                
   REAL       :: s=111.1, t=222.2, r=333.3
   CHARACTER(LEN=255) :: c=' '
   NAMELIST /cmd/ i,j,k,s,t,r,c            ! just add a variable here !!!!
   !---------------------------------------------------------------------------
   CALL GET_COMMAND(string)                ! get command line arguments
   string="&cmd "//string//" /"            ! add NAMELIST prefix and terminator
   READ(string,NML=cmd,iostat=ios,iomsg=message) ! internal read of NAMELIST
   if(iostat.ne.0)then
      write(*,*)'E-R-R-O-R: ',ios
      write(*,*)message
   endif
   WRITE(*,NML=cmd)                        ! use the values
END PROGRAM testit

and then you can call the program with syntax like:

   testit r=200e3  i=200
   testit "c='my character string' S=10,T=20.30,R=3e-2"
   testit K=33333,J=22222,I=11111

No need to convert from strings to numeric values, arrays and user-defined types can be used, complex values can be input ... just define the variable and add it to the NAMELIST definition.

Well, things are never that simple -- especially since, at this date you are probably working with an f95 compiler with some f2003 extensions. The following Bourne shell demonstrates using NAMELIST to read command line parameters with current versions of the g95 and gfortran compilers:

It shows how to avoid a problem with GET_COMMAND(), and one way to handle not having dynamic character variables. If your compiler does not support the f2003 ability to read a NAMELIST from an internal file, you will have to write the data to a file and then read it back. If it doesn't support GET_COMMAND_ARGUMENT(3f), you can use the very common GETARGS(3f) extension or see the F2KCLI package from WINTERACTER.


NAMELIST examples



Exploring NAMELIST

Miscellaneous files not yet completed