Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eval string/convert string to Expr

Tags:

julia

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
like image 601
Phuoc Avatar asked Jul 16 '26 11:07

Phuoc


2 Answers

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.)

like image 91
Braham Snyder Avatar answered Jul 19 '26 18:07

Braham Snyder


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
like image 42
Felipe Jiménez Avatar answered Jul 19 '26 20:07

Felipe Jiménez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!