[SOLVED] In SAS, is there a test for whether a function exists?


This Content is from Stack Overflow. Question asked by Rodney

I am creating a new function (trims). Before running that code however I would like to check if I’ve already created the function, and if so delete it.
The part that is not working for me is the first line, checking for the existence of a function.
I have tried variation, to the memtype (i.e. change “catalog” to “all”, or deleted it, and let it default.) I have also tried the cexist function. No luck. Help!

I’m trying to elimanate the WARNINGs the code produces if I don’t first delete the function…

        %if %sysfunc(exist(userfuncs.package1,catalog)) %then %do;
            /* delete previous function definition during debugging */
            options cmplib=work.userfuncs;
            proc fcmp outlib=work.userfuncs.package1;
               deletefunc trims;

        /* new function defintion */
        proc fcmp outlib=work.userfuncs.package1;
           function trims(f $, str $, clist $, mod $) $32767;
              from = 1;
              last = length(str);
              if upcase(f) in ('L', 'B') then from = findc(str, clist, 'K'||mod);
              if from=0 then return('');
              if upcase(f) in ('T', 'B') then last = findc(str, clist, 'K'||mod, -last); 
              if last=0 then return('');
              return(substr(str, from, last-from+1));      

I’m running this from SAS-EG 7.13, connecting to a Unix server



Your code is creating a SAS dataset named WORK.USERFUNCS. So if you want to test if a function named TRIMS exist in a package named PACKAGE1 just check if there are any observations in WORK.USERFUNCS where _KEY_="F.PACKAGE1.TRIMS".

The warning only occurs after you have set the CMPLIB option. So you can use the CMPLIB option to determine where you need to look to tell if the function exists or not.

%macro function_exist(function,mvar=sysrc);
%local dslist ;
%if not %symexist(&mvar) %then %global &mvar;
%* Force function name to uppercase ;
%let function=%qupcase(&function);
%* Get list of datasets to search from the CMPLIB system option ;
%let dslist=%qsysfunc(getoption(cmplib));
%let dslist=%sysfunc(lowcase(&dslist));
%let dslist=%sysfunc(compress(&dslist,()));
%let dslist=%sysfunc(tranwrd(&dslist,_no_displayloc_,));
%let dslist=%sysfunc(tranwrd(&dslist,_displayloc_,));

%* Set return to false in case non of the datasets exist ;
%let &mvar=0;
%if %length(&dslist) %then %do;

data _null_;
  set &dslist ;
  where _key_ like "F.%.&function" ;
  call symputx("&mvar",1);

%mend function_exist;

This Question was asked in StackOverflow by Rodney and Answered by Tom It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?