[erlang-questions] Beginners question on pattern matching

Chandru <>
Fri Oct 5 18:07:11 CEST 2007


On 05/10/2007, Alexander Lamb <> wrote:
> Hello List,
>
> I am starting on Erlang. I read most of the new Erlang book. However, I am
> lost with something really simple and probably stupid.
>
> I am reading a file, line by line.
>
> Each line is in the form
>
> "a_code" , a_date
>
> The quotes (") are present in the file, as well as the comma. For example:
>
> "C51CBA979E4311D67900201842D2EEE81",2003-08-07
>
>
> I would like to cut the string into pieces (to be able to modify it...).
> Again, this is a test to learn Erlang, I know how to do this in two lines of
> Ruby :-). I could also probably use a built in function to parse the string.
> But I would like to understand pattern matching and lists.
>
> So I wrote this, first read the file:
>
> start() ->
>
>  case file:open("ENRL_ENROLLMENT.csv",read) of
>
>  {ok, S} ->
>  Val = do_read(S),
>  file:close(S),
>  Result = process_lines(Val),
>  {ok,Result};
>
>  {error, Why} ->
>
>  {error, Why}
>
>  end.
>
> Then the lines:
>
> do_read(S) ->
>
>  case io:get_line(S,'') of
>
>  eof -> [];
>  Line -> [Line | do_read(S)]
>
>  end.
>
> Then process each line in the list of lines:
>
> process_lines(Lines) ->
>
>  [Date || [_Code | "," ++ Date] <- Lines].
>
>
> Something is wrong, because it compiles but here is what I get:
>
> 11> c(csv_convert.erl).
> {ok,csv_convert}
> 12> csv_convert:start().
> {ok,[]}
>
> If each line is actually a list of characters, why can't I match the pattern
> I want???
>
> Thanks for any hint (or examples) !!
>

For pattern matching with lists, you have to specify how to match each
element of the list. The way you've written your code, your are
looking for a regular expression capability in your pattern match
which doesn't exist.

Your code can be easily made to work like this.

do_read(S) ->
    case io:get_line(S,'') of
	eof -> [];
	Line -> [string:tokens(Line, ",") | do_read(S)]     %% Change here
    end.

process_lines(Lines) ->
    [Date || [_Code, Date] <- Lines].      %% and a change here.

cheers
Chandru



More information about the erlang-questions mailing list