Programming Erlang, 2 e., Chapter 2, Exercise 4, put_file()

David Christensen dpchrist@REDACTED
Sat Jan 1 20:15:01 CET 2022

On 1/1/22 4:45 AM, Fred Youhanaie wrote:
> Hi David
> I'll just add a few pointers to what has already been said.
> Since you're reusing previous code, you may find the ?MODULE macro 
> handy, e.g. spawn(?MODULE, loop, [Dir]), which should save you from 
> repeating the module name inside the code.

> Within the shell, you can use "flush()." to receive and print all the 
> messages in the shell's message queue, if any. 


(To be pedantic: when working exercises in a textbook, I try to use only 
the information that has been presented up to that point in the textbook.)

> For unknown messages, it is probably not a good idea to attempt to reply 
> to unexpected, perhaps even malformed, messages. The simplest pattern to 
> use in the server, while you're learning, would be something like:
> receive
>    ...
>    Any_msg -> %% make this the last clause in the receive block
>      io:format("Unknown message: ~p~n", [Any_msg])
> end

I thought of using a catch-all receive pattern and printing an error 
message as a default (last) case in the server, but did not know how to 
write the code.

That said, it is a better design; so, I will bend my rules and use it 
without understanding:

2022-01-01 10:48:28 dpchrist@REDACTED ~/sandbox/erlang
$ cat ex0204_server.erl
-export([start/1, loop/1]).

start(Dir) -> spawn(ex0204_server, loop, [Dir]).

loop(Dir) ->
	{Client, list_dir} ->
	    Client ! {self(), file:list_dir(Dir)};
	{Client, {get_file, File}} ->
	    Full = filename:join(Dir, File),
	    Client ! {self(), file:read_file(Full)};
	{Client, {put_file, File, Bytes}} ->
	    Full = filename:join(Dir, File),
	    Client ! {self(), file:write_file(Full, Bytes)};
	Any_msg ->
	    io:format("Unknown message: ~p~n", [Any_msg])

2022-01-01 10:51:42 dpchrist@REDACTED ~/sandbox/erlang
$ erl
Erlang/OTP 19 [erts-8.2.1] [source] [64-bit] [smp:8:8] 
[async-threads:10] [kernel-poll:false]

Eshell V8.2.1  (abort with ^G)
1> c(ex0204_server).
2> Server = ex0204_server:start(".").
3> Server ! {self(), list_dir}.
4> receive A -> A end.
5> Server ! {self(), {get_file, "hello.erl"}}.
6> receive B -> B end.
  {ok,<<"-module(hello).\n-export([start/0]).\n\nstart() ->\n 
io:format(\"hello, world!~n\").\n">>}}
7> Server ! {self(), {put_file, "foo", "bar\n"}}.
8> receive C -> C end.
9> Server ! bad_message.
Unknown message: bad_message
10> q().
2022-01-01 10:53:50 dpchrist@REDACTED ~/sandbox/erlang
$ cat foo

Thank you.


More information about the erlang-questions mailing list