字符串后的erlang异常:来自文件的readed行上的tokens

时间:2012-12-16 01:38:47

标签: erlang

尝试剪切一行,从文件中读取一个字符串列表。这导致总是一个我不知道要解决的异常。

    exception error: no function clause matching string:tokens1
(<<"Cascading Style Sheets CSS are an increasingly common way for website developers to control the look\n">>," ,.",[]) in function  readTest:run/1



-module(readTest).
-export([run/1]).

open_file(FileName, Mode) ->
    {ok, Device} = file:open(FileName, [Mode, binary]),
    Device.

close_file(Device) ->
    ok = file:close(Device).

read_lines(Device, L) ->
    case io:get_line(Device, L) of
        eof ->
            lists:reverse(L);
        String ->
            read_lines(Device, [String | L])
    end.

run(InputFileName) ->
    Device = open_file(InputFileName, read),
    Data = read_lines(Device, []),
    close_file(Device),
    io:format("Read ~p lines~n", [length(Data)]),
    Bla = string:tokens(hd(Data)," ,."),
    io:format(hd(Data)).

可能很容易失败。刚从erlang开始。

2 个答案:

答案 0 :(得分:1)

当您使用二进制标志打开文件时,行将被读取为二进制而不是列表(字符串)。 所以在你的代码中

 Bla = string:tokens(hd(Data)," ,."),

hd(Data)实际上是一个二进制文件,它导致string:tokens崩溃。 您可以从文件中删除二进制标志:打开,或者将二进制文件显式转换为列表:

 Bla = string:tokens(binary_to_list(hd(Data))," ,."),

答案 1 :(得分:1)

也可以拆分二进制文件而不将其转换为列表:

Bla = binary:split(Data, [<<" ">>, <<",">>, <<".">>], [global])

(见the documentation for binary:split/3。)