Problem: want to read content of a file (size less than 1MB) into a Erlang variable, do some text replacement and write modified contents to a new file. I am new to Erlang and want to use simple code with no error handling (use it from Erlang shell).
I have tried:
File = file:read_file("pbd4e53e0.html").
But when using
string:len(File).
I get
exception error: bad argument in function length/1 called as length({ok,<<">}) in call from string:len/1 (string.erl, line 66).
Next step is to do replacement:
re:replace(File, "<a href=\'pa", "<a href=\'../pa/pa", [{return, list}]).
Question 1: How should I read the file into an Erlang variable?
Question 2: Is the replacement ok?
For the first question, file:read_file/1
returns a tuple of {Status, Result}
, so the assignment should rather be like:
{ok, File} = file:read_file("pbd4e53e0.html").
Second, File
will be a binary, not a string, so you need to convert it to a string first:
Content = unicode:characters_to_list(File).
(You can provide the encoding argument as well)
Then string:len(Content)
will work as expected.
As for the replacements part, it's generally a very bad idea to use regex with HTML, but from the API point of view looks ok.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With