Environment Variables in Pascal

Here’s the Pascal translation of the environment variables example:

Our program demonstrates how to set, get, and list environment variables in Pascal.

program EnvironmentVariables;

uses
  SysUtils;

procedure PrintEnvironmentVariable(const Name: string);
var
  Value: string;
begin
  Value := GetEnvironmentVariable(Name);
  WriteLn(Name, ': ', Value);
end;

procedure ListEnvironmentVariables;
var
  EnvList: TStringList;
  i: Integer;
begin
  EnvList := TStringList.Create;
  try
    GetEnvironmentVariables(EnvList);
    WriteLn;
    for i := 0 to EnvList.Count - 1 do
      WriteLn(EnvList.Names[i]);
  finally
    EnvList.Free;
  end;
end;

begin
  // Set an environment variable
  SetEnvironmentVariable('FOO', '1');

  // Get and print environment variables
  PrintEnvironmentVariable('FOO');
  PrintEnvironmentVariable('BAR');

  // List all environment variables
  ListEnvironmentVariables;
end.

To set a key/value pair, we use SetEnvironmentVariable. To get a value for a key, we use GetEnvironmentVariable. This will return an empty string if the key isn’t present in the environment.

To list all key/value pairs in the environment, we use GetEnvironmentVariables which populates a TStringList with all environment variables. We then iterate through this list to print all the keys.

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

FOO: 1
BAR: 

PATH
SYSTEMROOT
TEMP
...
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. In Pascal, you can set an environment variable before running the program like this:

$ BAR=2 ./EnvironmentVariables
FOO: 1
BAR: 2
...

Note that the exact method of setting environment variables before running a program may vary depending on your operating system and Pascal compiler.