Obtaining the name of a variable as a string

11

1

Suppose that I have an arbitrary variable myVariable. Is there some function fun -- either built-in or one that I can define -- that will return a string "myVariable" when I pass it myVariable?

I would like the output...

myVariable = 123456;
fun[myVariable]

...to give the output...

"myVariable"

... (a string output) for some function fun. Do you have any suggestions? Thanks so much.

Andrew

Posted 2013-09-13T01:58:24.013

Reputation: 9 123

Question was closed 2014-07-24T14:03:22.480

15Looks like you need SymbolName[Unevaluated[myvar]]. – Leonid Shifrin – 2013-09-13T02:05:04.017

Answers

17

You can give the function one of the Hold Attributes.

SetAttributes[fun, HoldFirst]

Then as Leonid suggested

fun[var_] := SymbolName[Unevaluated@var] 

Without the hold attribute, this will not work.

RunnyKine

Posted 2013-09-13T01:58:24.013

Reputation: 32 260

5

Any of these could be a start:

ToString@((Trace@myVariable)[[1]])

Or:

StringCases[ToString[Hold[myVariable]],RegularExpression["Hold\\[([[:print:]]+)\\]"] -> "$1"][[1]]

xtian777x

Posted 2013-09-13T01:58:24.013

Reputation: 976

You don't need to use StringCases/regex if you use HoldForm instead of Hold – rm -rf – 2013-09-13T02:38:51.877