1. 29

Using Erlang to parse NTP data

  1.  

  2. 5

    I have to say that I found erlang rather unwieldy as a language and environment, but I did love its binary pattern-matching. And I miss it whenever I’m parsing a binary file format.

    1. 0

      I agree. I am not sure why other languages do not implement this. I was trying to do the same with other languages and it is a hilariously complicated task. I mostly dislike two things about Erlang:

      • OTP
      • the lack of an easy way of creating a single binary from a project
      1. 5
        • OTP

        Why? This is exactly what makes Erlang great.

        • the lack of an easy way of creating a single binary from a project

        This is described into Erlang nature and one of the greatest features - hot upgrades.

        1. 1

          Maybe it is just me. I need to spend more time on it. I never built anything that required OTP, and at the time I wanted to learn it I could not learn it fast enough.

          Hot upgrades sounds amazing in telco but in many industries, they want to have more control over what is running in production and have a solution to swap out the software using different methods.

          1. 2

            I never built anything that required OTP

            Supervisors are part of the OTP not “Erlang core”. gen_servers as well. So in Erlang virtually any application will use OTP.

    2. 3

      The greatest thing in pattern matching is that you can use previously matched numbers later, so if you have TLV encoded data then decoding it is a breeze, example:

      decode(<<?int, Size:8, Num:Size/integer-unit:8>>) -> Num;
      decode(<<?str, Size:8, Bin:Size/binary>>) -> Bin.
      
      1. 2

        Depending on your requirements, you have to be careful with this as it is not efficient, so double check with:

        export ERL_COMPILER_OPTIONS=bin_opt_info
        

        As per http://erlang.org/doc/efficiency_guide/binaryhandling.html you should punt the X:Size into a binary match done in the function.

        For most though it won’t matter.

      2. 3

        There are some fun caveats about performance with binary matching, too - this post is a decent overview of some of the gotchas.

        1. 1

          Thanks a lot! I am going to need this.

        2. 2

          I miss this syntax… I wish it was present i Haskell too!