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.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is not set.
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.
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.