I never use metaprogramming before. I imagined it makes a string to code? (it is probably wrong understanding at all) So I was thinking whether I can make use of it to process one of my text file. The file is like that
o = open("text.txt", "w")
println(o, "A\t1; B\t\"abc\"; C\t\"efg\";")
println(o, "A\t20; B\t\"ijkl\"; D\t\"mno\";")
‘;’ is used to defined each field. Each field includes a tab delineate of key and value pair. I would like to process it into a dictionary per line. For example line 1 to be the dictionary
Dict((“A”=>1, “B”=>“abc”, “C”=>“efg”))
I could do it by split and split. Since the raw string is already structured like dictionary definition, is it possible to directly proceed it into a dictionary? I know it is odd to do it like that. What’s the pros and cons of doing so?
Thank you very much!
No. Metaprogramming is for processing Julia syntax/generating julia code at compile time and it almost never involve parsing strings.
It’s not designed to do what you want and you shouldn’t use it. You should just treat this like a normal string parsing problem and find the right tool for that.
Okay I see. So even though I have a text file has the julia code as following each line. I cannot do that because when it see’s the file the program already running, not at compile time?
:A=>1, :B=>“abc”, :C=>“efg”
:A=>2, :B=>“abcd”, :C=>“efgs”
Kind of. A few points,
- Your data file is data, it’s not code. If all what you need is processing some data you should use the correct tool rather than converting it to code.
- There are many features in the language. If you invoke the whole language, the features you don’t need will make it very slow (since it’ll do unnecessary work) and very dangerous (since your data can basically run arbitrary code).
Another way to view this is that this is the difference between
eval in js.
Thank you for the explanations.
Just on the topic of metaprogramming I found this video to be extremely good for explaining when to consider using metaprogramming for things and why it is an easy “trap” to get caught in for things.
I think probably most telling bit is just how few instances there are of metaprogramming in the Julia standard library.