Part 10. Advanced tips and tricks

(c) 2017 by Barton Paul Levenson



Formats in strings

Instead of using a format number and a format statement:


    write (*, 10) num
10  format('num =', i5)


you can sandwich the whole format into the second argument of a read or write statement:


    write (*, "('num =', i5)") num


This can be useful to save space. It's not so great with really long formats.

Here's the example program from Part 3 written using this method:


program greetUser
    character(40) :: name

    write (*, '("Hi!  What's your name?  =>", $)')
    read  (*, *) name
    write (*, "('Hi, ', a, '!')") trim(name)
end program greetUser


Note how the string delimiters alternate to avoid confusing the compiler.



The semicolon operator

You can use a semicolon ( ; ) to put more than one statement on a line:


    a = 3.2; b = 4.7; c = 5.9


This can be a nice space-saver, but if you overdo it, you can make your code harder to read.



The inquire statement

The Fortran-77 standard introduced a new file-handling command, the inquire statement. There are two versions of it:


inquire(unit=u, varlist)

inquire(file=f, varlist)


where varlist is a list of useful variables, each with specifying keywords. You can, for example, list exist=ex, where ex is a logical variable that will wind up with .true. if the file exists under that name and .false. if it doesn't. You can also ask opened=op, where the result is .true. for a file that's open, .false. if it's closed.

Other clauses allowed include the usual err=, end=, and iostat=, along with a dozen others that pertain mostly to file type--for example, you can find the position and the next record number of a "direct-access" file. But again, that's for an advanced course. I myself never use direct-access files. That's why God made databases.



A final note

This is not all there is to Fortran. There are many more functions and statements that allow you to do all kinds of interesting things, especially mathematical things. But I have covered all you need for most science or math programming. And what I have not covered is in the Help system in Plato.





Page created:05/05/2017
Last modified:  06/13/2017
Author:BPL