M_CLI2

filedemo18.f90

Contents

Source

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
implicit none
character(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')

   print all,'--title or -T ... ',sget('title')
   print all,'-x .............. ',rget('X')
   print all,'-y .............. ',rget('Y')

contains

function get_env(NAME,DEFAULT) result(VALUE)
character(len=*),intent(in)          :: NAME
character(len=*),intent(in),optional :: DEFAULT
character(len=:),allocatable         :: VALUE
integer                              :: howbig
integer                              :: stat
integer                              :: length
   ! get length required to hold value
   length=0
   if(NAME /= '')then
      call get_environment_variable(NAME, length=howbig,status=stat,trim_name=.true.)
      select case (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 size
          if(allocated(value))deallocate(value)
          allocate(character(len=max(howbig,1)) :: VALUE)
          ! get value
         call get_environment_variable(NAME,VALUE,status=stat,trim_name=.true.)
          if(stat /= 0)VALUE=''
      end select
   else
      VALUE=''
   endif
   if(VALUE == ''.and.present(DEFAULT))VALUE=DEFAULT
end function get_env

end program demo18

Graphs

Files this one depends on