Thursday, July 29, 2010

erlang: Simple Debug macro

When testing things I need some quick way to debug "a la" printf() style. Old habits :)

Here's is the simple debug macro I use:
-define(DEBUG(Format, Args),
  io:format("~s.~w: DEBUG: " ++ Format, [ ?MODULE, ?LINE | Args])).
-define(DEBUG(Format, Args), true).
Write it down in a "debug.hrl" file, then you only need to add this line in any file header:
This simple macro gives you the module name and the line number. This saves me a lot of time.

Then you need to define the "debug" atom to let your macro do what you want. The compile:file/2 handles options for this, the syntax is {d, debug}

Wednesday, February 24, 2010

Filtering lines efficiently

Whenever you are dealing with log lines or that you're program is filtering data you always have to handle 'escaping' efficiently.

While developing a log module using a gen_event, I needed to escape simple quotes.
Sometime thoses quotes were already escaped...

I've found this regexp to handle gracefully the case:
re:replace( Bin, "(?<!\\\\)'", "\\\\'", [ global ] ).

Tuesday, February 23, 2010

Reading an openssl .priv.key file and extracting the key

Extracting the private key from a .priv.key file is simple.
The private key is encrypted using a AES-128 with your passphrase.

The initial vector is also stored in the file, you can extract it directly from the first line:
get_salt( <<"Salted__", Salt:8/binary, Rest/binary>> ) ->
        {Salt, Rest}.