Search code examples
sassas-macro

calculation inside char value


I have string value like "some text {5+1.5}", and would like to calculate it inside data step. (This value is from column, but it doesn't matter).

I have code, that was executed correctly but with errors inside macro. But if execute it without macro, there is no errors. I would like to execute it inside macro, how can i fix error? Without using options NOERRORABEND NODMSSYNCHK NOSYNTAXCHECK;. Algorithm is to change using tranwrd "{" to "%sysevalf(" and "}" to ")".

CODE THAT WORK CORRECTLY, BUT THERE IS ERROR IN LOG:

%macro t;
data have_in_macro;
%let value=%sysfunc(tranwrd(
                          %sysfunc(tranwrd(
                                        "some text {5+1.5}",%str(}),%str(%))
                              )),%str({),%str(sysevalf)%str(%()
                ));

                %let value=%sysfunc(tranwrd(
                            %str(&value),%str(sysevalf),%str(%%)%str(sysevalf)
                ));
                t=&value;
run;
%mend t;

%t;

CODE THAT WORK CORRECTLY WITHOUT ERRORS, BUT WITHOUT USING MACRO:

data have;
%let value=%sysfunc(tranwrd(
                          %sysfunc(tranwrd(
                                        "some text {5+1.5}",%str(}),%str(%))
                              )),%str({),%str(sysevalf)%str(%()
                ));

                %let value=%sysfunc(tranwrd(
                            %str(&value),%str(sysevalf),%str(%%)%str(sysevalf)
                ));
                t=&value;
run;

INPUT:

some text {5+1.5}

OUTPUT:

some text 6.5

ERROR USING MACRO:

ERROR: %SYSEVALF must be followed by an expression enclosed in parentheses.

P.S. This code is just sample to call error that i get using my algorithm calling tranwrd.


Solution

  • If you're using a data _null_ step you can use data step functions, not macro functions.

    This works for me - no errors.

    I broke it into two lines one to replace the { with %sysevalf( and } with ).

    EDIT: Use RESOLVE() to evaluate the string.

    data have;
    yourStringVariable = "some text {5+1.5}";
    run;
        
      %macro t(input_dsn= , output_dsn = );  
        data &output_dsn.;
        set &input_dsn.;
         *replace {;
         text_string2 = tranwrd(yourStringVariable, '{', '%sysevalf(');
         *replace };
         text_string3 = resolve(tranwrd(text_string2, '}', ')'));
    
        run;
        
    %mend t;
    
    %t(input_dsn=have, output_dsn=want);;
    
    proc print data=want;
    run;