Environment Variables in Chapel

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in Chapel.

use IO;
use OS;

proc main() {
    // To set a key/value pair, use setenv. To get a
    // value for a key, use getenv. This will return
    // an empty string if the key isn't present in the
    // environment.
    OS.setenv("FOO", "1");
    writeln("FOO: ", OS.getenv("FOO"));
    writeln("BAR: ", OS.getenv("BAR"));

    // Use OS.env to list all key/value pairs in the
    // environment. This returns an associative array of strings.
    // Here we print all the keys.
    writeln();
    for key in OS.env.keys() {
        writeln(key);
    }
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ chpl environment-variables.chpl -o environment-variables
$ ./environment-variables
FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
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.

$ BAR=2 ./environment-variables
FOO: 1
BAR: 2
...

In Chapel, we use the OS module to interact with environment variables. The setenv function is used to set environment variables, while getenv retrieves their values. The OS.env associative array provides access to all environment variables.

Note that unlike Go, Chapel doesn’t have a direct equivalent to strings.SplitN for parsing environment variables. Instead, we can directly access the key-value pairs from the OS.env associative array.