arraysfortranfortran-namelist

Read array sections in namelist


Consider a namelist containing two-dimensional arrays. For example, the following program reads from a file "input.dat".

program test
    use :: iso_fortran_env

    implicit none

    integer :: ierr, unit, i
    real(kind=kind(0.0d0)), allocatable :: p(:, :)

    namelist /VAR_p/ p

    allocate(p(2,2))
    open(newunit=unit, file='input.dat', status='old', iostat=ierr)
    read(unit, nml=VAR_p, iostat=ierr)
    close(unit)

    do i = 1, size(p, 1)
        write(output_unit, '(F4.2," ",F4.2)') p(i,1), p(i,2)
    end do
end program test

One can provide the array p in "input.dat" as

! input.dat
&VAR_p
p(1,1) = 1.2
p(1,2) = 3.2
p(2,1) = 1.0
p(2,2) = 0.0
/

With this input the program runs fine. Nevertheless, I would rather prefer to provide the array p line-by-line. Something like

! input.dat
&VAR_p
p(1,:) = (1.2, 3.2)
p(2,:) = (1.30, 0.0)
/

Is there a syntax to achive that?


Solution

  • There is indeed a syntax to specify an array section in a namelist record. It's close to the requested form, but not quite.

    In a namelist record, the item (1.30, 0.0) specifies a complex value not an array constructor (which means the generalization to (1.3, 0.0, 1.2) isn't a valid value). Instead you simply want to specify a list of values: 1.3, 0.0:

    &VAR_p
    p(1,:) = 1.2, 3.2
    p(2,:) = 1.30, 0.0
    /
    

    There are some restrictions of note:

    In this second case, if there are fewer values on the right-hand side than elements on the left, then it's as though the right-hand side were padded with null values.