What is the idiomatic way of doing...

Wiger Ulf ulf.wiger@REDACTED
Thu Apr 10 09:14:57 CEST 2003

From: "HP Wei" <hp@REDACTED>
> ---------------------------------------
> Suppose I have this file:
> % test1.txt content
> label1    v1
> label2    v2
> (2) Is there an idiomatic way of getting the list of tuples as in the
>     previous case ??
> (3) What about getting one tuple at a time ???

Here's a suggestion for the non-erlang syntax file:


-export([file1/1, file2/1]).

%% read the whole file at once
file1(F) ->
   {ok, Binary} = file:read_file(F),
   Lines = string:tokens(binary_to_list(Binary),
   [list_to_tuple(string:tokens(L," \t")) || L <- Lines,
                                             length(L) > 0].

%% read one line at a time
file2(F) ->
   {ok, Fd} = file:open(F, [read]),

read_terms(Fd) ->
   read_terms(Fd, io:get_line(Fd, ""), []).

read_terms(Fd, eof, Acc) ->
read_terms(Fd, L, Acc) ->
   [list_to_tuple(string:tokens(L," \t\n")) |
    read_terms(Fd, io:get_line(Fd,""), [])].

For the file with erlang tuples, you should perhaps study the implementation
of file:consult/1 (you will find it in the 'kernel' application). It
actually does take one tuple at a time. The solution is similar to my
read_terms/3 above, but it uses io:read/2 instead of io:get_line/2.


More information about the erlang-questions mailing list