# Clearing a global variable from inside a Module

This is a highly simplified version of a initialization problem I have with a complicated program with many (about 100) modules.

If one enters: X=42; Clear[X]; the X value is removed. Fine. Now consider 3 simple modules:

ClearMyX0[]:=Module[{}, Clear[X]];

ClearMyX1[]:=Module[{}, s=Symbol["X"]; Clear[s]];

ClearMyX2[]:=Module[{}, Clear["X"] ];


and try

X=42; ClearMyX0[]; X=42; ClearMyX1[]; X=42; ClearMyX2[];


(Print statements removed for brevity.) I find that ClearMyX0 works as expected. ClearMyX2 also works but ClearMyX1 does not. I have no idea why - my presumption about those two was the opposite.

So far I have not seen web documentation explaining that behavior. Please give me a reference.

• after s = Symbol["X"]; there is not infomation about X in s, only the value is assigned.
– Kuba
Jan 16, 2016 at 22:32
• Note that Clear is HoldAll. So Clear[s] means quite literally what it says. @Kuba's comment applies as well, of course. There is actually no renaming going on in any of these examples (I thought that could have been your problem at first glance), so I think there is nothing unexpected here. Jan 16, 2016 at 22:34
• You should be aware of the fact that a Module without a local variable doesn't change anything to what you are trying to do. If you want to remove a symbol whose name is stored in a variable as a string, you could use: ClearMyX3[] := Module[{s}, s = "X"; Clear[Evaluate@s]]. (note that I have localized s, so in that case the Module isn't useless which is what you probably want to do in the long term and it shows that this will also work...). In general I would never suggest to write code which needs to clear globals, can you explain why you think you need this? Jan 18, 2016 at 10:27

If you are expecting Clear[x] to clear definitions of x, don't expect anything more from Clear[s].

So you can go with:

X = 5; s = "X"; Clear[#] &@s
X


X

Or, as pointed by Albert Retey, with Clear[Evaluate@s].

Maybe you don't want to use strings, then:

X = 5; s = ToExpression["X", StandardForm, Unevaluated];

Clear[#] &@s
X


works too. Some additional ways and comments can be found in Mr. Wizard's answer in: How to Clear variables represented as a list of strings?