bambi
bambi

Reputation: 384

Calling a macro from another macro's if condition

I am trying to create a very simple macro to determine if a macro parameter was supplied or not. However, I am obtaining an error with the message "required operator not found in expression: %is_def(&param1)." What is wrong with this code?

%macro is_def(var);
    (%length(&var) > 0);
%mend;

%macro do_something(param1);

    %if %is_def(&param1) %then %do;
        %put parameter was provided;
    %end;
    %else %do;
        %put parameter was NOT supplied;
    %end;

%mend;

%do_something(5);

Upvotes: 0

Views: 63

Answers (1)

Quentin
Quentin

Reputation: 6378

You macro %is_def is a function style macro. You have an extra semicolon in it which is causing the error.

As written, you call %is_def(hello) the macro will return this code:

(5 > 0);

The 5 is because hello is 5 characters long. Note the semicolon at the end, you don't want that semicolon.

As written, the %IF statement in %Do_Something will end up like:

%if (5 > 0); %then %do;

And looking at that, you can see why the semicolon causes the problem.

To fix, you should remove the semicolon, i.e. change to:

%macro is_def(var);
    (%length(&var) > 0)
%mend;

Another possible enhancement would be to have the is_def macro return simply a 1 or 0 for true or false, rather than return (5 > 0). For that, you could do:

%macro is_def(var);
    %eval(%length(&var) > 0)
%mend;

There is an EXCELLENT paper on this subject (testing for blank parameters), which considers this method as well as several others, and ends with a utility macro %IsBlank. Suggest you check it out: http://changchung.com/download/022-2009.pdf.

Upvotes: 3

Related Questions