# f = p; p = 2; How to clear the value of p without explicitly writing the variable p in the code?

I had a problem on a program of mine that I could avoid by developing the code through other ways. On the other hand, I still do not know how to solve the simple problem below:

Consider these two definitions:

f = p; p = 2;

One can use Clear[p] to clear the value of p, which will lead the output of f to be p, instead of 2.

Is there a way to clear the value of p through the definition of the variable f? That is, without explicit writing the variable p.

By using Definition[f], the output is "f=p", but if I try to pick the variable "p" from the definition, trough Definition[f][], I cannot apply Clear on it, since p is automatically evaluated to 2, thus the application of Clear in the last case leads to "Clear", instead of "Clear[p]".

Context on where this problem may appear: Consider a larger program in which the variable name p was automatically built and depends on the input of the user (in this case the name of the variable will typically be larger, but let us stick with the name p). If the name of the variable was generated automatically, and depends on the user input, I cannot explicitly type in the code "Clear[p]". One can use Clear[f], but this will not clear the value of p. To sove the issue, I simply avoided using variables whose names depend on the user input, nonetheless, I would like to know a solution for the problem above.

Thanks.

f = p; p = 2;
Last[MapAt[Clear, First[OwnValues[f]], 2]]
p


p

Maybe instead of f = p you should use f = Hold[p] or f = Hold[#]&[p] so the above becomes

ReleaseHold[MapAt[Clear, f, 1]]


which maybe looks a bit better

• Great! Actually the first answer is the one I was looking for. Thanks @Coolwater. – DCRodrigues May 5 '17 at 17:21
• Alternatively: ClearAll @@ (Hold[f] /. OwnValues[f]) – Kuba May 30 '17 at 20:27

Try this

p = 2;
With[{a = p}, f = a]