This question does sound weird as Elixir should have immutability but this is actually what is happening!
I have this code:
html = # get the HTML from somewhere but this html is correct
{:ok, file} = File.open("html", [:write])
IO.binwrite(file, html)
File.close(file)
new_html = remove_unused(html)
{:ok, file} = File.open("new_html", [:write])
IO.binwrite(file, new_html)
File.close(file)
new_html
end
defp remove_unused(body) do
regex = Regex.scan(~r/\[[\s\S]*?\.start\][\s\S]*?\[[\s\S]*?\.end\]/, body)
if(regex == []) do
IO.write regex
body
else
{:ok, file} = File.open("regex", [:write])
IO.binwrite(file, regex)
File.close(file)
indexed = Enum.with_index(regex)
Enum.map(indexed, fn({data, index}) ->
{:ok, file} = File.open("#{index}", [:write])
IO.binwrite(file, "#{data}")
File.close(file)
end)
Enum.reduce(indexed, body, fn({line, _index}, buffer_body) ->
String.replace(buffer_body, line, "", global: false)
end)
end
end
Where I want to replace [something.start]
, [something.end]
and everything between them with an empty string.
When the method returns new_html
that data is malformed. html
is changed right after assigning even though it is not being reassigned at a later point and the overall html is empty (it has closing statemenets but almost nothing in-between).
(I checked this with using the files for debugging)
Now look at this… if I change the return value of the function with html
instead of new_html
the html
is not malformed and all of the data in the files is correct, but that way I can’ access the value of new_html
when I invoke the function! (reading the data from the file is not an option)