|
|
|
|
|
|
|
|
|
|
Yorick
1.2.3: Conditional ExecutionThe design of the q_out function can be improved. As written, each output file will contain only a single wave. You might want the option of writing several waves into a single file. Consider this alternative:
The if statement executes its body (the redefinition of file) if and only if its condition (!is_stream(file)) is true. Any scalar number may serve as a condition -- a non-zero value is ``true'', and the value zero is ``false''. The is_stream function returns 1 (true) when its argument is a file object (a ``data stream''), and 0 (false) otherwise. In particular, if file is a text string (like "q.out"), is_stream returns 0. The unary operator ! is logical negation, that is, ``not''. Hence, if the file argument is not already a file object, the new q_out presumes it is the name of a file, which it creates, redefining file as the associated file object. Thus, after the first line of the function body, file will be a file object, even if a file name was passed into the function. Furthermore, since the parameter file is local to q_out, none of this hocus pocus will have any effect outside q_out. The second trick in the new q_out is the reappearance of a return statement. The original calling sequence:
has the same result as before -- the if condition is true, so the file is created, then the wave data is written. This time the file object is returned, only to be discarded because q_out was invoked as a procedure. When the file object disappears, the file closes. But if q_out were invoked as a function, the file object can be saved, which keeps the file open:
Now the file ` |