program demo18
!> @(#) using environment variables!!!! Environment variable values may be used to construct!! the string passed to set_args(3) relatively easily.!!!!!! building the string passed to set_args(3) using an environment variable!! env TITLE='my new title' demo18 !!!! Using the "env_fallback" mode where every option automatically !! has an option set!!!! env DEMO18_X=111 DEMO18_Y=3000 DEMO18_TITLE='my title' demo18 !!use M_CLI2, only : set_args, sget, rget, set_mode
implicitnonecharacter(len=*),parameter :: all='(*(g0))'print *,'demo18: using environment variables'call set_mode('env_fallback')
call set_args(' --title:T "' &
& // get_env('TITLE','default title')// &
&'" -X 10.20 -Y 30.456')
printall,'--title or -T ... ',sget('title')
printall,'-x .............. ',rget('X')
printall,'-y .............. ',rget('Y')
containsfunction get_env(NAME,DEFAULT) result(VALUE)
character(len=*),intent(in) :: NAME
character(len=*),intent(in),optional :: DEFAULT
character(len=:),allocatable :: VALUEinteger :: howbig
integer :: statinteger :: length
! get length required to hold value length=0if(NAME /= '')thencallget_environment_variable(NAME, length=howbig,status=stat,trim_name=.true.)
selectcase (stat)
case (1)
!x!print *, NAME, " is not defined in the environment. Strange..."VALUE=''case (2)
!x!print *, "This processor doesn't support environment variables. Boooh!"VALUE=''case default
! make string to hold value of sufficient sizeif(allocated(value))deallocate(value)
allocate(character(len=max(howbig,1)) :: VALUE)
! get valuecallget_environment_variable(NAME,VALUE,status=stat,trim_name=.true.)
if(stat /= 0)VALUE=''endselectelseVALUE=''endifif(VALUE == ''.and.present(DEFAULT))VALUE=DEFAULT
endfunction get_env
endprogram demo18