[erlang-questions] http:request
Ladislav Lenart
lenartlad@REDACTED
Fri Apr 22 10:33:23 CEST 2011
Hello,
see my answer below.
On 22.4.2011 09:49, Kostis Sagonas wrote:
> Carlo Bertoldi wrote:
>> Il 21/04/2011 17:10, Carlo Bertoldi ha scritto:
>>> Good afternoon,
>>> I have a problem with http:request.
>>>
>> <snip>
>>>
>>> Result = http:request(get, {CompleteUrl, [{"User-Agent", "Erl-bot"}]}, [], []),
>>> io:format("Result = ~p~n", [Result]).
>>>
>>> Occasionally I don't see Result printed, but a nice error:
>>> ** Reason for termination ==
>>> ** {{badmatch,{16,6,18}},
>>
>> Hello, I discovered the cause of the badmatch: it was due to the debug macro I've defined.
>> Here it is:
>>
>> -define(DBG(Str, Args),
>> {Year, Month, Day} = date(),
>> {Hour, Min, Sec} = time(),
>> io:format("~2.10.0B/~2.10.0B/~4B ~2.10.0B:~2.10.0B:~2.10.0B [~p:~p] - ", [Day, Month,
>> Year, Hour, Min, Sec, ?MODULE, ?LINE]), io:format(Str, Args)).
>>
>> Can someone explain me what I did wrong here? Why should I obtain a badmatch on {Hour, Min, Sec} = time() ?
>
> A typical reason for this is if you used the macro in some context where variables named Hour, Min, and Sec already existed. This is called name capture and is a typical problem of macros. You should
> carefully examine all places in the code where this macro is used. Alternatively, you can try to minimize the risk of name capture by changing the macro to e.g.:
>
> -define(DBG(Str, Args),
> {Year__, Month__, Day__} = date(),
> {Hour__, Min__, Sec__} = time(),
> io:format("~2.10.0B/~2.10.0B/~4B ~2.10.0B:~2.10.0B:~2.10.0B [~p:~p] - ", [Day__, Month__, Year__, Hour__, Min__, Sec__, ?MODULE, ?LINE]), io:format(Str, Args)).
If you plan to use ?DBG macro more than once in the same function,
you might want to wrap it in an anonymous fun to prevent its
variables from leaking to the function where the macro is used:
-define(DBG(Str, Args), fun () ->
{Year__, Month__, Day__} = date(),
{Hour__, Min__, Sec__} = time(),
io:format("~2.10.0B/~2.10.0B/~4B ~2.10.0B:~2.10.0B:~2.10.0B [~p:~p] - ", [Day__, Month__, Year__, Hour__, Min__, Sec__, ?MODULE, ?LINE]),
io:format(Str, Args),
ok
end()).
With this modification, the following should be possible:
some_fun() ->
?DBG("foo", []),
?DBG("bar", []),
ok.
However, as Kostis said, the following will still raise a
badmatch error:
some_other_fun(Year__) ->
?DBG("foo", []),
ok.
HTH,
Ladislav Lenart
More information about the erlang-questions
mailing list