How to parse Fortran command line arguments using NAMELIST
While searching around for a pure Fortran 90+ way to parse command line arguments and/or input files, I stumbled across Exploring NAMELIST by John S. Urban. John's article shows a way to use Fortran's NAMELIST feature to quickly parse arbitrary command line arguments while providing sane default behavior.
Like usual, I decided to overdevelop a simple idea.
The complete sample is up on github. Assuming you've got an interface declaration in scope for get_command_arguments
, here's what you'd see as an end consumer:
IMPLICIT NONE
CHARACTER(LEN=255) :: string, message
INTEGER :: status
! Declare and initialize a NAMELIST for values of interest
INTEGER :: i=1, j=2
REAL :: s=3.3, t=4.4
NAMELIST /cmd/ i, j, s, t
! Get command line arguments as a string ready for NAMELIST
CALL get_command_arguments(string, "&cmd", "/")
READ (string, NML=cmd, IOSTAT=status, IOMSG=message)
IF (status /= 0) THEN
WRITE (*,*) 'Error: ', status
WRITE (*,*) 'Message: ', message
CALL EXIT (status)
END IF
! Echo the results
WRITE (*, NML=cmd)
END PROGRAM namelist_cli
With a little mucking around, the same NAMELIST could be used to read an input file from disk, allow the user to override individual options on the command line (say, for parametric studies), and also to dump the full setup into an output file for tracking purposes.