% This LaTeX document was generated using the LaTeX backend of PlDoc,
% The SWI-Prolog documentation system



\section{library(main): Provide entry point for scripts}

\label{sec:main}

\begin{tags}
\mtag{See also}- \verb$library(optparse)$ for comprehensive option parsing. \\- \verb$library(prolog_stack)$ to force backtraces in case of an
uncaught exception. \\- XPCE users should have a look at \verb$library(pce_main)$, which
starts the GUI and processes events until all windows have gone.
\end{tags}

This library is intended for supporting PrologScript on Unix using the
\verb$#!$ magic sequence for scripts using commandline options. The entry
point \predref{main}{0} calls the user-supplied predicate \predref{main}{1} passing a list of
commandline options. Below is a simle \const{echo} implementation in Prolog.

\begin{code}
#!/usr/bin/env swipl

:- initialization(main, main).

main(Argv) :-
    echo(Argv).

echo([]) :- nl.
echo([Last]) :- !,
    write(Last), nl.
echo([H|T]) :-
    write(H), write(' '),
    echo(T).
\end{code}

\vspace{0.7cm}

\begin{description}
    \predicate{main}{0}{}
Call \predref{main}{1} using the passed command-line arguments. Before calling
\predref{main}{1} this predicate installs a signal handler for \verb$SIGINT$
(Control-C) that terminates the process with status 1.

    \predicate[det]{argv_options}{3}{+Argv, -RestArgv, -Options}
Generic transformation of long commandline arguments to options.
Each --Name=Value is mapped to Name(Value). Each plain name is
mapped to Name(true), unless Name starts with \verb$no-$, in which
case the option is mapped to Name(false). Numeric option values
are mapped to Prolog numbers.

\begin{tags}
    \tag{See also}
\verb$library(optparse)$ provides a more involved option library,
providing both short and long options, help and error handling.
This predicate is more for quick-and-dirty scripts.
\end{tags}
\end{description}

