[erlang-questions] How to match on a nested record against a dict

Rob Charlton rob@REDACTED
Mon Nov 23 09:37:32 CET 2009


Hi Jarrod,

First off, to get the record definitions for #dns_rec and #dns_rr, you 
need to include this line in your module (normally near the top):

-include_lib("kernel/src/inet_dns.hrl").

Now I would code it something like:

    receive
        {udp, _Socket, IP, InPortNo, Packet} ->
            process_dnsrec(Sub,inet_dns:decode(Packet)),
            receiver(Sub);

...

process_dnsrec(Sub,{error,E}) ->

    %% do some error handling here (if required)

    ;

process_dnsrec(Sub,{ok,#dnsrec{anlist=Responses}) ->

    %% Responses is a list of #dns_rr records, so we want to handle them one at a time

    process_dnsrec1(Sub,Responses).

process_dnsrec1(_,[]) ->

    %% no more responses

    ;

process_dnsrec1(Sub,[#dns_rr{domain=Dom}|Rest]) ->
    %% lookup the domain field from the #dns_rr record

    case dict:find(Dom,Sub) of

       [Result] ->

            io:format("Interesting domain ~p~n",[Result]);

       error ->

            %% do nothing for non-interesting domains

           ok

    end,

    process_dnsrec1(Sub,Rest).


Cheers

Rob


Jarrod Roberson wrote:
> I have the following data structure: it is a record as specified in
> inet_dns.hrl:
>
> {ok,{dns_rec,{dns_header,0,true,'query',true,false,false,false,false,0},
>                    [],
>                    [{dns_rr,"_see._tcp.local",ptr,in,0,0,
>                             "jhr@REDACTED",undefined,[],
>                             false}],
>                    [],[]}}
>
> I have the following code where Sub is a dict:
>
> receiver(Sub) ->
>     receive
>         {udp, _Socket, IP, InPortNo, Packet} ->
>             DnsRec = inet_dns:decode(Packet),
>                io:format("~n~nFrom: ~p~nPort: ~p~nData:
> ~p~n",[IP,InPortNo,DnsRec]),
>                receiver(Sub);
>            stop ->
>                true;
>          AnythingElse ->
>                %io:format("RECEIVED: ~p~n",[AnythingElse]),
>                receiver(Sub)
>        end.
>
> I want to match on the "_see._tcp.local" and see if it is in the dns_rr
> record and only do the io:format() if that is in my subscriptions dict.
> Can anyone point me in the right direction of what idiom to use? This
> pattern matching stuff is difficult for us olde school if () ers
>
>   



More information about the erlang-questions mailing list