No. No. No. No. The whole point of a subroutine is that you can use it again - both within this program and in other programs.
Letâs put the subroutine in a module and in a separate file. This is just the subroutine surrounded by âmodule print_string_mâ / âend moduleâ.
Multiple files and modules may be overkill here, but it is essential for larger projects.
File: print_string.f90 - nothing special about the name
module print_string_m
implicit none
contains
! Write string to stdout with maximum line length n
! Break lines at spaces, if there is a <space> in next n characters.
subroutine print_string(string,n)
character(len=*), intent(in) :: string
integer, intent(in) :: n
integer left ! leftmost unprocessed character
integer last ! last non-<space> character in string
integer nout ! number of character to print on this line
left = 1
last = len_trim(string)
do while (left+n.le.last)
nout = index(string(left:left+n-1),substring=' ',back=.true.)
if (nout==0) nout=n ! print n characters if no <space> found
write(*,"(a)") string(left:left+nout-1)
left = left + nout
end do
if (left<=last) write(*,"(a)") string(left:last)
end subroutine print_string
end module
Now put the calling code in a separate file and âuseâ the module.
File: prog04.f90
program prog04
use print_string_m
implicit none
character(len=200) :: stringin
character(len=50) :: string2
stringin = 'the kat kissed the dog and ate his banana. '//&
'The banana was too big for its mouth so it had to sneeze.'
string2 = 'The quick, brown fox jumped over the lazy dog'
call print_string(stringin,40)
write(*,*)
call print_string(string2,10)
write(*,*)
call print_string('... and we can print a literal string, too',12)
end
I compiled this with the commands
gfortran -Wall -fcheck=all -c print_string.f90
gfortran -Wall -fcheck=all -o prog04.exe prog04.f90 print_string.o
It generates
the kat kissed the dog and ate his
banana. The banana was too big for its
mouth so it had to sneeze.
The
quick,
brown fox
jumped
over the
lazy dog
... and we
can print a
literal
string, too