Environment Variables in D Programming Language

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 D.

import std.stdio;
import std.process;
import std.string;
import std.array;

void main()
{
    // To set a key/value pair, use environment.set
    // To get a value for a key, use environment.get
    // This will return null if the key isn't present in the environment
    environment["FOO"] = "1";
    writeln("FOO: ", environment.get("FOO"));
    writeln("BAR: ", environment.get("BAR"));

    // Use environment.toAA to get all key/value pairs in the environment
    // This returns an associative array of strings
    // Here we print all the keys
    writeln();
    foreach (key; environment.toAA().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 null.

$ rdmd environment_variables.d
FOO: 1
BAR: 

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 rdmd environment_variables.d
FOO: 1
BAR: 2
...

In D, we use the std.process module to work with environment variables. The environment object provides methods to get and set environment variables. The toAA() method returns an associative array of all environment variables, which we can then iterate over to list all keys.

Note that in D, we use rdmd to compile and run D scripts in one step, similar to how go run works in Go. For larger projects, you would typically use dmd to compile your D code into an executable.