15
$\begingroup$

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.

$\endgroup$
1
  • 16
    $\begingroup$ Looks like you need SymbolName[Unevaluated[myvar]]. $\endgroup$ Commented Sep 13, 2013 at 2:05

2 Answers 2

19
$\begingroup$

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.

$\endgroup$
0
7
$\begingroup$

Any of these could be a start:

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

Or:

StringCases[ToString[Hold[myVariable]],RegularExpression["Hold\\[([[:print:]]+)\\]"] -> "$1"][[1]] 
$\endgroup$
1
  • $\begingroup$ You don't need to use StringCases/regex if you use HoldForm instead of Hold $\endgroup$ Commented Sep 13, 2013 at 2:38

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.