Command Line Flags in Co-array Fortran

Our program demonstrates the use of command-line flags in Co-array Fortran. While Co-array Fortran doesn’t have a built-in flag parsing module like Go’s flag package, we can implement a simple version using subroutines and the command line arguments.

program command_line_flags
  use iso_fortran_env
  implicit none

  character(len=100) :: word = "foo"
  integer :: numb = 42
  logical :: fork = .false.
  character(len=100) :: svar = "bar"
  
  integer :: i, argc
  character(len=100) :: arg

  call parse_arguments()
  
  print *, "word:", trim(word)
  print *, "numb:", numb
  print *, "fork:", fork
  print *, "svar:", trim(svar)
  
contains

  subroutine parse_arguments()
    argc = command_argument_count()
    do i = 1, argc
      call get_command_argument(i, arg)
      select case (arg)
        case ("-word")
          if (i < argc) then
            call get_command_argument(i+1, word)
            i = i + 1
          end if
        case ("-numb")
          if (i < argc) then
            call get_command_argument(i+1, arg)
            read(arg, *) numb
            i = i + 1
          end if
        case ("-fork")
          fork = .true.
        case ("-svar")
          if (i < argc) then
            call get_command_argument(i+1, svar)
            i = i + 1
          end if
      end select
    end do
  end subroutine parse_arguments

end program command_line_flags

This program demonstrates a basic implementation of command-line flag parsing in Co-array Fortran. Here’s how it works:

  1. We define variables for each flag with default values.
  2. The parse_arguments subroutine processes the command-line arguments.
  3. We use command_argument_count() to get the number of arguments and get_command_argument() to retrieve each argument.
  4. A select case statement is used to handle different flags.
  5. For string and integer flags, we check if there’s a value following the flag and update the corresponding variable.
  6. For the boolean flag -fork, we simply set it to true if present.
  7. After parsing, we print out the values of all flags.

To compile and run the program:

$ gfortran -o command_line_flags command_line_flags.f90
$ ./command_line_flags -word opt -numb 7 -fork -svar flag
word: opt
numb: 7
fork: T
svar: flag

If you omit flags, they will retain their default values:

$ ./command_line_flags -word opt
word: opt
numb: 42
fork: F
svar: bar

Note that this implementation is basic and doesn’t include features like automatic help text generation or strict error checking. In a real-world application, you might want to implement more robust argument parsing and error handling.

Also, Co-array Fortran doesn’t have a direct equivalent to Go’s flag.Args() for trailing arguments. If you need to handle additional positional arguments, you would need to modify the parse_arguments subroutine to collect them separately.