[erlang-questions] variable unsafe just in macros

Richard A. O'Keefe <>
Tue Aug 12 03:03:55 CEST 2008


On 10 Aug 2008, at 9:31 am, Lasaro wrote:
> -define(debug,true).
>
> -ifdef(debug).
> -define(DEBUG(Msg),
> case Msg of
>         [] ->
>             io:format("{~p@~p:~p}", [?MODULE,?LINE,self()]);
>         [[_|_]=Format, [_|_]=Param] ->
>             io:format(lists:append(["{~p@~p:~p} ",Format]), [?MODULE,?
> LINE,self()|Param]);
>         [_|_] ->
>             io:format("{~p@~p:~p} "++Msg, [?MODULE,?LINE,self()]);
>         _ ->
>             io:format("{~p@~p:~p} wrong debug call", [?MODULE,?
> LINE,self()])
>     end).
> -else.
> -define(DEBUG(_M), true).
> -endif.

First observation: lists:append([X,Y]) would be simpler as X++Y.
Second observation: where are the comments explaining how this is to  
be used?
Third observation: surely a macro definition did not give you a warning
about an unsafe variable?  Surely that happened later, when you called  
it.
So we need to see the call as well, but it probably wants to use a
variable Param for its own purposes.

Simple change: use 'hd' and 'tl' instead of variable names.

-define(DEBUG(Message),
     case Message
       of [] ->
              io:format("{~p@~p:~p}",
                        [?MODULE,?LINE,self()])
        ; [[_|_], [_|_]] ->
              io:format("{~p@~p:~p} " ++ hd(Message),
                        [?MODULE,?LINE,self()|hd(tl(Message))])
        ; [_|_] ->
              io:format("{~p@~p:~p " ++ Message,
                        [?MODULE,?LINE,self()])
        ; _ ->
              io:format("{~p@~p:~p wrong debug call",
                        [?MODULE,?LINE,self()])
     end).

Fourth observation: where's the newline being written?




More information about the erlang-questions mailing list