Environment Variables in Prolog
Our first example demonstrates how to work with environment variables in Prolog. Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables.
:- use_module(library(process)).
main :-
% To set a key/value pair, use setenv/2
% To get a value for a key, use getenv/2
% This will fail if the key isn't present in the environment
setenv('FOO', '1'),
(getenv('FOO', FOO) -> writeln('FOO: ' || FOO) ; writeln('FOO not set')),
(getenv('BAR', BAR) -> writeln('BAR: ' || BAR) ; writeln('BAR not set')),
nl,
% Use environ/1 to list all key/value pairs in the environment
% This returns a list of Key=Value atoms
environ(Env),
maplist(print_env_key, Env).
print_env_key(KeyValue) :-
atomic_list_concat([Key, _], '=', KeyValue),
writeln(Key).
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is not set.
$ swipl -q -t main -s environment_variables.pl
FOO: 1
BAR not set
USER
SHELL
PATH
...
FOO
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
$ env BAR=2 swipl -q -t main -s environment_variables.pl
FOO: 1
BAR: 2
...
In this Prolog version:
- We use the
process
library which provides predicates for working with environment variables. setenv/2
is used to set environment variables.getenv/2
is used to get environment variables. It fails if the variable is not set, so we use a conditional to handle both cases.environ/1
is used to get all environment variables.- We use
maplist/2
with a custom predicateprint_env_key/1
to print all environment variable keys. atomic_list_concat/3
is used to split the Key=Value atom into its components.
Note that the exact behavior might vary depending on your Prolog implementation. This example uses SWI-Prolog syntax and predicates.