次の例は、標準の POSIX 関数 getenv() および putenv() を呼び出すことによって、COBOL プログラムから環境変数に アクセスする方法と環境変数を設定する方法を示しています。
getenv() と putenv() は C 関数なので、BY VALUE によって引数を渡さなければなりません。文字ストリングは、ヌル終了ストリングを指し示す BY VALUE ポインターとして渡さなければなりません。これらの関数を呼び出すプログラムは、NODYNAM オプションと PGMNAME(LONGMIXED) オプションを指定してコンパイルします。
CBL pgmname(longmixed),nodynam
Identification division.
Program-id. "envdemo".
Data division.
Working-storage section.
01 P pointer.
01 PATH pic x(5) value Z"PATH".
01 var-ptr pointer.
01 var-len pic 9(4) binary.
01 putenv-arg pic x(14) value Z"MYVAR=ABCDEFG".
01 rc pic 9(9) binary.
Linkage section.
01 var pic x(5000).
Procedure division.
* Retrieve and display the PATH environment variable
Set P to address of PATH
Call "getenv" using by value P returning var-ptr
If var-ptr = null then
Display "PATH not set"
Else
Set address of var to var-ptr
Move 0 to var-len
Inspect var tallying var-len
for characters before initial X"00"
Display "PATH = " var(1:var-len)
End-if
* Set environment variable MYVAR to ABCDEFG
Set P to address of putenv-arg
Call "putenv" using by value P returning rc
If rc not = 0 then
Display "putenv failed"
Stop run
End-if
Goback.