erlangejabberderlang-shellerlangweberlang-driver

Erlang - Parse data from the enclosed curly braces


Erlang experts, I am getting a data like the following from ejabberd server

I(<0.397.0>:mod_http_offline:38) : Data of Fromu {jid,"timok","localhost",
                                              "25636221451404911062246700",
                                              "timok","localhost",
                                              "25636221451404911062246700"}

I am a very much confused about this data type. All I need is to get timok from the enclosed flower braces. {} But not sure how to get the value. Any code to get the value will be much helpful. Currently I am printing the values using the below code

?INFO_MSG("Data of Fromu ~p",[_From]),

Thanks once again for your time and effort.


Solution

  • That's an erlang record (it's a tuple, first element an atom, other elements lists/strings/binaries).

    Recommended:

    Ejabberd has a jid record definition (line 411):

    -record(jid, {user = <<"">> :: binary(),
            server = <<"">> :: binary(),
            resource = <<"">> :: binary(),
            luser = <<"">> :: binary(),
            lserver = <<"">> :: binary(),
            lresource = <<"">> :: binary()}).
    

    It's in the ejabberd/include/jlib.hrl file, so you should be able make it known to your module by including it this way:

     -include_lib("ejabberd/include/jlib.hrl").
    

    Now, in your module to access the (first) "timok" element of your data, you can use the erlang record syntax (assuming JidData contains the data mentioned above):

    Out = JidData#jid.user.
    

    Not recommended:

    As records are, behind their appearance, tuples, you can also access the nth element of the tuple

    Out = element(2,JidData).
    

    Or simply use pattern matching:

    {_, Out, _, _, _, _} = JidData.
    

    Use Record Definitions

    A record is basically syntaxic sugar on a tuple. It remains a tuple and can be treated as such. They're easy to work with, but you should do what you can to avoid treating a record as a tuple, unless you really know what you're doing.

    And because in this case you don't even control the record definition, you really should use it, otherwise changes in the definition, following an update, will invalidate your code.