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.
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:
Then use the line filter to get uppercase lines:
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.