Home > Software engineering >  Julia: Metaprogramming, evaluate string to string assignment?
Julia: Metaprogramming, evaluate string to string assignment?

Time:10-06

Is it possible to evalute a string to an expression containing a string ? To give a mwe :

eval(Meta.parse("x = 2"))

is evaluted to:

x = 2

But I would like x to be a string itself. My naive try in making x a string:

eval(Meta.parse("x = "2" "))

which i would like to be evaluted to

x = "2"

gives me an error. Therefore, my question is: Is it possible to do this, using only strings ?

CodePudding user response:

You need to escape the quotation marks:

eval(Meta.parse("x = \"2\""))

CodePudding user response:

@August has answered the question, however just one another way usually more practical when doing metaprogramming:

julia> eval(:(x= "2"));

julia> x
"2"

This nicely works with interpolation:

julia> z="hello";

julia> eval(:(x2 = $z));

julia> x2
"hello"
  • Related