Line Filters in Fortran
Here’s the translation of the Go line filter program to Fortran, along with explanations in Markdown format suitable for Hugo:
A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep
and sed
are common line filters.
Here’s an example line filter in Fortran that writes a capitalized version of all input text. You can use this pattern to write your own Fortran line filters.
program line_filter
use, intrinsic :: iso_fortran_env, only: stdin => input_unit, &
stdout => output_unit, &
stderr => error_unit
implicit none
character(len=1024) :: line
integer :: io_status
do
! Read a line from standard input
read(stdin, '(A)', iostat=io_status) line
if (io_status < 0) exit ! End of file
if (io_status > 0) then
write(stderr, '(A)') 'Error reading input'
stop 1
end if
! Convert the line to uppercase
call to_upper(line)
! Write the uppercased line to standard output
write(stdout, '(A)') trim(line)
end do
contains
subroutine to_upper(str)
character(len=*), intent(inout) :: str
integer :: i
do i = 1, len_trim(str)
select case(str(i:i))
case('a':'z')
str(i:i) = achar(iachar(str(i:i)) - 32)
end case
end do
end subroutine to_upper
end program line_filter
This Fortran program reads lines from standard input, converts them to uppercase, and writes them to standard output. Here’s a breakdown of how it works:
We use the
iso_fortran_env
module to get standard input, output, and error units.We use a
do
loop to continuously read lines from standard input.The
read
statement reads a line into theline
variable. Theiostat
parameter allows us to check for end-of-file or errors.If we’ve reached the end of the file (io_status < 0), we exit the loop.
If there’s an error reading (io_status > 0), we print an error message to stderr and stop the program.
We call the
to_upper
subroutine to convert the line to uppercase.We write the uppercased line to standard output.
The
to_upper
subroutine uses ado
loop andselect case
to convert each lowercase letter to uppercase.
To try out our line filter, first make a file with a few lowercase lines.
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/lines
Then compile and use the line filter to get uppercase lines.
$ gfortran line_filter.f90 -o line_filter
$ cat /tmp/lines | ./line_filter
HELLO
FILTER
This Fortran version achieves the same functionality as the original program, reading lines from standard input, converting them to uppercase, and writing them to standard output.