\chapter{Nice-looking output}
\label{chap:formatting}

\section{Formatted output}
\label{sec:printf}

A common occurrence when you're writing a script---particularly when
you intend for the script to be used by others, and you'd like the
output to be reasonably self-explanatory---is that you want to output
something along the following lines:
\begin{code}
The coefficient on X is Y, with standard error Z
\end{code}
where \texttt{X}, \texttt{Y} and \texttt{Z} are placeholders for
values not known at the time of writing the script; they will be
filled out as the values of variables or expressions when the script
is run. Let's say that at run time the replacements in the sentence
above should come from variables named \texttt{vname} (a string),
\texttt{b} (a scalar value) and \texttt{se} (also a scalar value),
respectively.

Across the spectrum of programming languages there are basically two
ways of arranging for this. One way originates in the \textsf{C}
language and goes under the name \texttt{printf}. In this approach we
(a) replace the generic placeholders \texttt{X}, \texttt{Y} and
\texttt{Z} with more informative \textit{conversion specifiers}, and
(b) append the variables (or expressions) that are to be stuck into
the text, in order. Here's the hansl version:
\begin{code}
printf "The coefficient on %s is %g, with standard error %g\n", vname, b, se
\end{code}
The value of \texttt{vname} replaces the conversion specifier
``\texttt{\%s},'' and the values of \texttt{b} and \texttt{se} replace
the two ``\texttt{\%g}'' specifiers, left to right. In relation to
hansl, here are the basic points you need to know: ``\texttt{\%s}''
pairs with a string argument, and ``\texttt{\%g}'' pairs with a
numeric argument.

The \textsf{C}-derived \texttt{printf} (either in the form of a
function, or in the form of a command as shown above) is present in
most ``serious'' programming languages. It is extremely versatile, and
in its advanced forms affords the programmer fine control over
the output.

In some scripting languages, however, \texttt{printf} is reckoned
``too difficult'' for non-specialist users. In that case some sort of
substitute is typically offered. We're skeptical: ``simplified''
alternatives to \texttt{printf} can be quite confusing, and if at some
point you want fine control over the output, they either do not
support it, or support it only via some convoluted mechanism. A
typical alternative looks something like this (please note,
\texttt{display} is \textit{not} a hansl command, it's just
illustrative):
\begin{code}
display "The coefficient on ", vname, "is ", b, ", with standard error ", se, "\n"
\end{code}
That is, you break the string into pieces and intersperse the names of
the variables to be printed. The requirement to provide conversion
specifiers is replaced by a default automatic formatting of the
variables based on their type. By the same token, the command line
becomes peppered with mutiple commas and quotation marks. If this looks
preferable to you, you are welcome to join one of the gretl mailing
lists and argue for its provision!

Anyway, to be a bit more precise about \cmd{printf}, its syntax goes
like this:
\begin{flushleft}
  \texttt{printf \emph{format}, \emph{arguments}}
\end{flushleft}
The \emph{format} is used to specify the precise way in which you want
the \emph{arguments} to be printed.

\subsection{The format string}
\label{sec:fmtstring}

In the general case the \cmd{printf} format must be an expression that
evaluates to a string, but in most cases will just be a \textit{string
  literal} (an alphanumeric sequence surrounded by double
quotes). However, some character sequences in the format have a
special meaning. As illustrated above, those beginning with a
percent sign (\texttt{\%}) are interpreted as placeholders for the
items contained in the argument list. In addition, special characters
such as the newline character are represented via a combination
beginning with a backslash (\verb|\|).

For example,
\begin{code}
printf "The square root of %d is (roughly) %6.4f.\n", 5, sqrt(5)
\end{code}
will print 
\begin{code}
The square root of 5 is (roughly) 2.2361.
\end{code}

Let's see how:
\begin{itemize}
\item The first special sequence is \verb|%d|: this indicates that we
  want an integer at that place in the output; since it is the
  leftmost ``percent'' expression, it is matched to the first
  argument, that is 5.
\item The second special sequence is \verb|%6.4f|, which stands for a
  decimal value with 4 digits after the decimal separator\footnote{The
    decimal separator is the dot in English, but may be different in
    other locales.} and at least 6 digits wide; this will be matched
  to the second argument. Note that arguments are separated by
  commas. Also note that the second argument is neither a scalar
  constant nor a scalar variable, but an expression that evaluates to
  a scalar.
\item The format string ends with the sequence \verb|\n|, which
  inserts a newline.
\end{itemize}

The conversion specifiers in the square-root example are relatively
fancy, but as we noted earlier \texttt{\%g} will work fine for
almost all numerical values in hansl. So we could have used the
simpler form:
\begin{code}
printf "The square root of %g is (roughly) %g.\n", 5, sqrt(5)
\end{code}
The effect of \texttt{\%g} is to print a number using up to 6
significant digits (but dropping trailing zeros); it automatically
switches to scientific notation if the number is very large or very
small. So the result here is
\begin{code}
The square root of 5 is (roughly) 2.23607.
\end{code}

The escape sequences \verb|\n| (newline), \verb|\t| (tab), \verb|\v|
(vertical tab) and \verb|\\| (literal backslash) are recognized. To
print a literal percent sign, use \verb|%%|.

Apart from those shown in the above example, recognized numeric
formats are \verb|%e|, \verb|%E|, \verb|%f|, \verb|%g|, \verb|%G| and
\verb|%x|, in each case with the various modifiers available in C. The
format \verb|%s| should be used for strings.
As in C, numerical values that form part of the format (width and or
precision) may be given directly as numbers, as in \verb|%10.4f|, or
they may be given as variables. In the latter case, one puts asterisks
into the format string and supplies corresponding arguments in
order. For example,

\begin{code}
  scalar width = 12 
  scalar precision = 6 
  printf "x = %*.*f\n", width, precision, x
\end{code}

If a matrix argument is given in association with a numeric format,
the entire matrix is printed using the specified format for each
element. A few more examples are given in table \ref{tab:printf-ex}.
\begin{table}[htbp]
  \centering
   {\small
    \begin{tabular}{p{0.45\textwidth}p{0.3\textwidth}}
      \textbf{Command} & \textbf{effect} \\
      \hline
      \verb|printf "%12.3f", $pi| & 3.142 \\
      \verb|printf "%12.7f", $pi| & 3.1415927 \\
      \verb|printf "%6s%12.5f%12.5f %d\n", "alpha",| \\
      \verb|   3.5, 9.1, 3| &
      \verb| alpha     3.50000     9.10000 3| \\
      \verb|printf "%6s%12.5f%12.5f\t%d\n", "beta",| \\
      \verb|   1.2345, 1123.432, %11| &
      \verb|  beta     1.23450  1123.43200 11| \\
      \verb|printf "%d, %10d, %04d\n", 1,2,3| & 
      \verb|1,          2, 0003| \\
      \verb|printf "%6.0f (%5.2f%%)\n", 32, 11.232| & \verb|32 (11.23%)| \\
      \hline
    \end{tabular}
  }
  \caption{Print format examples}
  \label{tab:printf-ex}
\end{table}

\subsection{Output to a string}
\label{sec:sprintf}

A closely related effect can be achieved via the \cmd{sprintf}
function: instead of being printed directly the result is stored in a
named string variable, as in
\begin{code}
  string G = sprintf("x = %*.*f\n", width, precision, x)
\end{code}
after which the variable \texttt{G} can be the object of further
processing.

\subsection{Output to a file}
\label{sec:outfile}

Hansl does not have a file or ``stream'' type as such, but the
\cmd{outfile} command can be used to divert output to a named text
file. To start such redirection you must give the name of a file; by
default a new file is created or an existing one overwritten but the
\option{append} can be used to append material to an existing file.
Only one file can be opened in this way at any given time. The
redirection of output continues until the command \cmd{end outfile} is
given; then output reverts to the default stream.

Here's an example of usage:
\begin{code}
  printf "One!\n"
  outfile "myfile.txt"
    printf "Two!\n"
  end outfile
  printf "Three!\n"
  outfile "myfile.txt" --append
    printf "Four!\n"
  end outfile
  printf "Five!\n"
\end{code}
After execution of the above the file \texttt{myfile.txt} will contain
the lines
\begin{code}
Two!
Four!  
\end{code}

Three special variants on the above are available. If you give the
keyword \texttt{null} in place of a real filename along with the write
option, the effect is to suppress all printed output until redirection
is ended. If either of the keywords \texttt{stdout} or \texttt{stderr}
are given in place of a regular filename the effect is to redirect
output to standard output or standard error output, respectively.

This command also supports a \option{quiet} option: its effect is to
turn off the echoing of commands and the printing of auxiliary
messages while output is redirected. It is equivalent to doing
\begin{code}
  set echo off 
  set messages off
\end{code}
before invoking \cmd{outfile}, except that when redirection is ended
the prior values of the \texttt{echo} and \texttt{messages} state
variables are restored.

\section{Graphics}

The primary graphing command in hansl is \texttt{gnuplot} which, as
the name suggests, in fact provides an interface to the
\textsf{gnuplot} program. It is used for plotting series in a dataset
(see part~\ref{part:hp-data}) or columns in a matrix. For an account
of this command (and some other more specialized ones, such as
\texttt{boxplot} and \texttt{qqplot}), see the \GCR.

%%% Local Variables: 
%%% mode: latex
%%% TeX-master: "hansl-primer"
%%% End: 
