DATA Step, Macro, Functions and more

%global error while looping

Reply
Contributor
Posts: 20

%global error while looping

Hi,
I had this code which was running fine.


%macro check_list;
%global list;
%if &list= %then %do;
%let list=“myname”;

(Other code)

%end;
%mend check_list;


Now I had to loop this process so I updated it to below.

%macro loop;
%do i = 1 to 4;

%macro check_list;
%global list&i;
%if &&list&i= %then %do;
%let list&i=“myname”;

(Other code)
%end;
%mend loop;

%loop;

%end;
%mend check_list;


But now I am getting this error.

Error: attempt to %global a name (list2) which exists in a local environment.

How can I get rid of this and run the program successfully.

Any suggestions is appreciated. Thanks in advance.


Super User
Posts: 6,934

Re: %global error while looping

Posted in reply to nickspencer

First suggestion:  untangle the macro definitions so that a human has a prayer of understanding the code.  There is hardly ever a reason to define one macro inside the definition of another macro.  Don't do it.  You can still have a macro call another macro, even if the macro being called is defined later.

 

Second suggestion:  check that "other code" section to make sure it doesn't assign a value to &LIST2 when &i=1.

Super User
Super User
Posts: 8,279

Re: %global error while looping

Posted in reply to nickspencer

The reason you cannot make a variable GLOBAL if it already exists in a local symbol table is because there is no way for you to assign it a value or reference its value. It will be hidden by the existing macro variable with the same name in a closer scope.

 

The only real purpose in defining a macro variable %GLOBAL inside a macro is if you want to make sure the values you assign to it will live after the macro exits.   But if the macro variable already exists when your macro starts running then it will exist after your macro ends.

 

So just make the macro that it causing the error smart enough NOT to cause the error.  Have it test whether the macro variable variable already exists before trying to define it as global. 

%macro check_list;
%if not %symexist(list) %then %global list;
%if &list= %then %do;
%let list=“myname”;

(Other code)

%end;
%mend check_list;
Ask a Question
Discussion stats
  • 2 replies
  • 70 views
  • 0 likes
  • 3 in conversation