String as a variable name

From this StackOverflow thread, in Julia 1.3 there is convenient syntax var"name" to evaluate a name string into a variable. The documentation is here (thanks to @Tamas_Papp). See examples below with Julia 1.4.2.

julia> a = [1, 2, 3];

julia> var"a"
3-element Array{Int64,1}:
 1
 2
 3

or create a new variable by assignment

julia> var"msg" = "Hello, world!";

julia> msg
"Hello, world!"
3 Likes

?@var_str, like all other literal macros.

3 Likes

It does not allow you to do anything new. It’s merely a different syntax to write out a variable name that looks like a string.

Doesn’t it let you create and refer to variables whose names are not valid identifiers, which is not normally possible without metaprogramming?

julia> 1 = 2
ERROR: syntax: invalid assignment location "1" around REPL[1]:1
Stacktrace:
 [1] top-level scope at REPL[1]:1

julia> var"1" = 2
2
5 Likes

Errrr, well,

  1. That’s still just “a different syntax”, and
  2. It has nothing to do with what this thread is about…

I’m not convinced this should ever be done, but, it seems to do what you wanted:

julia> boo = ("name1", "name2", "name3")
("name1", "name2", "name3")

julia> parsley = (55.6, 33.9, 3692.3)
(55.6, 33.9, 3692.3)

julia> for i in 1:length(boo)
          eval(Meta.parse("var\"" * boo[i] * "\" = " * string(parsley[i])))
       end

julia> name1
55.6

julia> name2
33.9

julia> name3
3692.3

Never ever use parse to do metaprogramming.

8 Likes

Is it possible to convert a variable name to a string or vice versa in a marco? I’m working with dataframes, but I might also try to do the same thing with dictionaries.

1 Like