12

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.

István Zachar
  • 47,032
  • 20
  • 143
  • 291
Andrew
  • 10,569
  • 5
  • 51
  • 104

2 Answers2

19

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
  • 33,088
  • 3
  • 109
  • 176
7

Any of these could be a start:

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

Or:

StringCases[ToString[Hold[myVariable]],RegularExpression["Hold\\[([[:print:]]+)\\]"] -> "$1"][[1]]
xtian777x
  • 1,018
  • 8
  • 14