First Erlang gotcha - Variables that don’t vary and pattern matching
Well, I had hoped that my first foray into Erlang might have got further - instead, I fell for the first trick in the book…
I wanted to write a little udp server which I could grow into something more interesting. The server side seemed to work just fine, but for some reason I simply couldn’t get the server response to reach the client. The client had code of the form :
query(Msg) ->
{ok, Socket} = gen_udp:open(0, [binary]),
ok = gen_udp:send(Socket, “localhost”, 4545, term_to_binary(Msg)),
Value = receive
{udp, Socket, _, _, Bin} = Msg ->
% deal with the response message
. . . .
Of course, the Msg variable is already defined by the time the response returns, so the first pattern in receive will never match (presuming that the response is different to the query).
I really shouldn’t be copy-pasting code (which is how Msg ended up in two places in the same function. However, I’m obviously going to have to get my eye in for this sort of thing if I’m going to be doing much with Erlang. It took me far too long to find this obvious bug!

