Line Filters in Co-array Fortran
Here’s the translation of the line filter example from Go to Co-array Fortran:
Our line filter program reads input from standard input, processes it, and then prints a derived result to standard output. This example writes a capitalized version of all input text.
program line_filter
use iso_fortran_env, only: input_unit, output_unit, error_unit
implicit none
character(len=1024) :: line
integer :: io_status
do
read(input_unit, '(A)', iostat=io_status) line
if (io_status /= 0) exit
call to_upper(line)
write(output_unit, '(A)') trim(line)
end do
if (io_status > 0) then
write(error_unit, '(A)') 'Error reading input'
stop 1
end if
contains
subroutine to_upper(string)
character(len=*), intent(inout) :: string
integer :: i
do i = 1, len_trim(string)
if (string(i:i) >= 'a' .and. string(i:i) <= 'z') then
string(i:i) = achar(iachar(string(i:i)) - 32)
end if
end do
end subroutine to_upper
end program line_filter
This Co-array Fortran program implements a line filter that capitalizes all input text. Here’s how it works:
We use the
iso_fortran_env
module to get standard unit numbers for input, output, and error streams.We read input line by line using a do-loop and the
read
statement. Theiostat
parameter allows us to check for end-of-file or errors.For each line, we call the
to_upper
subroutine to convert it to uppercase.We write the uppercase line to standard output using the
write
statement.If there’s an error during reading (indicated by
io_status > 0
), we print an error message to the error unit and stop the program with a non-zero exit code.The
to_upper
subroutine converts a string to uppercase by iterating through each character and replacing lowercase letters with their uppercase equivalents using ASCII character codes.
To try out our line filter, first make a file with a few lowercase lines:
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/lines
Then use the line filter to get uppercase lines:
$ cat /tmp/lines | ./line_filter
HELLO
FILTER
Note that Co-array Fortran doesn’t have built-in support for command-line piping like in the original example. You would need to compile the Fortran program into an executable named line_filter
before running the above command.
This example demonstrates how to create a simple line filter in Co-array Fortran, reading from standard input, processing the text, and writing to standard output. It showcases basic I/O operations, string manipulation, and error handling in Fortran.