Reputation: 1103
Is there a method to convert a string to Expr? I tried the following but it doesn't work:
julia> convert(Expr, "a=2")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Expr
This may have arisen from a call to the constructor Expr(...),
since type constructors fall back to convert methods.
julia> Expr("a=2")
ERROR: TypeError: Expr: expected Symbol, got String
in Expr(::Any) at ./boot.jl:279
Upvotes: 7
Views: 5372
Reputation: 581
parse
doesn't work here anymore. Now you need Meta.parse
:
eval(Meta.parse("a = 2"))
(As pointed out by Markus Hauschel in a comment.)
Upvotes: 14
Reputation: 127
Note that as of Julia 1.0, this no longer works. Generally if you want to be evaluating string expression in Julia 1.0 you should be using expressions all the way through, e.g. :(a=2)
julia> parse("a=2")
ERROR: MethodError: no method matching parse(::Expr)
julia> @show eval(:(a=2))
eval($(Expr(:quote, :(a = 2)))) = 2
2
Upvotes: 0
Reputation: 505
As Colin said, to convert to Expr
(or Symbol
) you use parse
.
And then to evaluate the resulting Expr
you use eval
.
Both together:
julia> eval(parse("a = 2"))
2
Upvotes: 2