4

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?

4

1 回答 1

9

对于第一个问题,file:read_file/1返回一个 元组{Status, Result},因此分配应该是这样的:

{ok, File} = file:read_file("pbd4e53e0.html").

其次,File将是二进制文件,而不是字符串,因此您需要先将其转换为字符串:

Content = unicode:characters_to_list(File).

(您也可以提供编码参数

然后string:len(Content)将按预期工作。

至于替换部分,将正则表达式与 HTML 一起使用通常是一个非常糟糕的主意,但从 API 的角度来看看起来还不错。

于 2013-03-30T10:08:56.317 回答