Hi,
First I’ll quickly sketch the goal:
I’ve been trying to read an input file which has a couple of blocks (control,system,electrons,ions,cell). Each block starts with a & and ends with a /. Inside each block there are several keywords and values. For each of these blocks I want to create a dictionary and store the key-value pairs.
Now, since the loop inside each block is exactly the same, I thought this would a perfect opportunity to get some metaprogramming/code generation in there.
I’ve been experimenting with stuff to try and get this to work, but I can’t seem to figure out just how exactly do it. I’ve looked at the documentation and other resources on this, but I don’t fully get how code inside function declarations gets parsed.
The code looks like this:
function read_QEInput(filename,T=Float32)
blocks = [:control,:system,:electrons,:ions,:cell]
:($(block...) = [Dict{Symbol,Any}() for i=1:5])
open(filename) do f
while !eof(f)
line = readline(f)
for block in blocks
if contains(line,"&$(Symbol(block))")
line = readline(f)
while !contains(line,"/")
if contains(line,"!")
line = readline(f)
continue
end
split_line = filter(x->x!="",strip.(split(line,",")))
for s in split_line
key,val = String.(strip.(split(s,"=")))
:($block[Symbol(key)] = isnull(tryparse(T,val)) ? val : get(tryparse(T,val)))
end
line = readline(f)
end
end
end
end
end
return control,system,electrons,ions,cell
end
What I’m trying to accomplish is first to initiate the dictionaries, basically to get to an expression like this:
control,system,electrons,ions,cell = [Dict{Symbol,Any} for i=1:5]
,
then to basically generate an if contains(line,"&block")
section for each of the blocks that I define.
However none of my tries amounted to anything that actually worked. So I guess my questions are: am I trying to do something that is impossible? Am I approaching it from the wrong angle?
I know I could just define another function or maybe a macro which handles this block of code, but I think it would be more clear like this + it might be instructive to learn about the workings of the language.
Thanks!