Enter Home Page

Exploring NAMELIST

Fortran 2003 NAMELIST-based command line argument parsing

Fortran NAMELIST groups can be used to create a unprecedentedly simple method of passing values via the command line. The following example program simply needs an initialized variable added to the NAMELIST and it automatically is available as a command line argument

program testit
implicit none
character(len=255)           :: message ! use for I/O error messages
character(len=:),allocatable :: string  ! stores command line argument
integer                      :: ios

! declare and initialize a namelist
integer    :: i=1, j=2, k=3
real       :: s=111.1, t=222.2, r=333.3
real       :: arr(3)=[10.0,20.0,30.0]
character(len=255) :: c=' '
namelist /cmd/ i,j,k,s,t,r,c            ! just add a variable here !!!!

   string=get_namelist()
   write(*,*)'STRING=',string
   read(string,nml=cmd,iostat=ios,iomsg=message) ! internal read of namelist
   if(ios.ne.0)then
      write(*,'("ERROR:",i0,1x,a)')ios, trim(message)
   endif
   write(*,nml=cmd)                        ! use the values
contains
function get_namelist() result (string)
character(len=:),allocatable :: string         ! stores command line argument
integer :: command_line_length
   call get_command(length=command_line_length)   ! get length needed to hold command
   allocate(character(len=command_line_length) :: string)
   call get_command(string) 
   ! trim off command name and get command line arguments
   string=adjustl(string)//' '
   string=string(index(string,' '):)
   string="&cmd "//string//" /"                   ! add namelist prefix and terminator
end function get_namelist
end program testit

and then you can call the program with NAMELIST 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.