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:

  1. We use the process library which provides predicates for working with environment variables.
  2. setenv/2 is used to set environment variables.
  3. 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.
  4. environ/1 is used to get all environment variables.
  5. We use maplist/2 with a custom predicate print_env_key/1 to print all environment variable keys.
  6. 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.