Environment Variables in Ada
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.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
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 Ada, we use the Ada.Environment_Variables
package to work with environment variables. The Set
procedure is used to set a variable, and the Value
function is used to retrieve a variable’s value. If a variable doesn’t exist, Value
will raise a Constraint_Error
exception, which we catch to print an empty string for non-existent variables.
To list all environment variables, we use the Iterate
procedure, which calls a specified procedure for each environment variable. In this example, we define a local procedure Print_Key
that prints only the name of each variable.
Note that Ada’s approach to environment variables is more type-safe than some other languages, as it uses exceptions to handle missing variables rather than returning a special value.