Command Line Flags in Fortran

Here’s the translation of the Go code example to Fortran, with explanations in Markdown format suitable for Hugo:

Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

Fortran doesn’t have a built-in module for parsing command-line arguments like Go’s flag package. However, we can use the intrinsic get_command_argument subroutine to achieve similar functionality. Here’s an example of how to implement basic command-line flag parsing in Fortran:

program command_line_flags
    implicit none
    
    character(len=32) :: arg
    integer :: i, num_args
    character(len=32) :: word = "foo"
    integer :: numb = 42
    logical :: fork = .false.
    character(len=32) :: svar = "bar"

    num_args = command_argument_count()

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

    print *, "word:", trim(word)
    print *, "numb:", numb
    print *, "fork:", fork
    print *, "svar:", trim(svar)
    
    ! Print remaining arguments
    print *, "tail:"
    do i = 1, num_args
        call get_command_argument(i, arg)
        if (arg(1:1) /= "-") then
            print *, trim(arg)
        end if
    end do
end program command_line_flags

To experiment with the command-line flags program, first compile it and then run the resulting executable directly.

$ gfortran command_line_flags.f90 -o command_line_flags

Try out the built program by giving it values for all flags:

$ ./command_line_flags -word opt -numb 7 -fork -svar flag
word: opt
numb:           7
fork: T
svar: flag
tail:

Note that if you omit flags, they automatically take their default values:

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

Trailing positional arguments can be provided after any flags:

$ ./command_line_flags -word opt a1 a2 a3
word: opt
numb:          42
fork: F
svar: bar
tail:
a1
a2
a3

Unlike Go’s flag package, this basic implementation doesn’t automatically generate help text or handle errors for undefined flags. You would need to implement these features manually if required.

Also, note that in this Fortran implementation, the order of the flags matters, and all flags must be preceded by their respective identifiers (e.g., -word, -numb, etc.). This differs from Go’s more flexible flag parsing.