1

Is it possible somehow to retrieve variable value by its name (name represented as string)?

% we are calling foo function as foo(3)
foo(Param) ->
    Var1 = Param * 2,
    % some magic code here which can evaluate 
    % "Var1" string to Var1's value (6)
    ok.

I want to implement (if it is possible) some kind of logger macro, like

Param = 3*4,
% This should write "My parameter value is 12" to log
?LOG("My parameter value is $Param"). 

Thanks.

2
  • If you are very specific about about logging you can use existing library called lager. It is widely used logging library which uses parse_transform. Commented Dec 21, 2013 at 7:33
  • @Marutha I am not very specific about logging. I just want to have convenient way to log message (without writing a lot of tildes and brackets in code: io:format("My parameter value is ~p~n", [Param]).) . Commented Dec 22, 2013 at 19:42

3 Answers 3

1

The common way to log is to have formatting string and list of parameters. However your idea is achievable through usage of parse transform.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Parse transform is what I need.
1

Thanks to Dmitry Belyaev for mentioning parse transform. Say we have logging code:

?dump("My parameter value is $Param")

What I need here is to parse variables within format string ("My parameter value is $Param") with some regular expression. This format string contains single var name (Param). And we need to insert io_lib:format function call (by transforming original AST) with modified format string:

print_message(io_lib:format("My parameter value is ~p~n", [Param]))

In result we can archive required behavior:

Bar = "hello",
Buzz = buzz123,    
?dump("Say $Bar to $Buzz"),
% => example:19: Say "hello" to buzz123

You can look at my implementation here

Comments

0

For toy problems you could use:

io:format("My parameter value is ~p~n", [Param]).

See io_lib and io.

Alternatively:

error_logger:info_report/1

or other error_logger functions.

The logging library lager is commonly used.

2 Comments

Code like io:format("My parameter value is ~p~n", [Param]). is really annoying sometimes (all those tildes and brackets...) Thats why I would like to use simpler code like ?LOG("My parameter value is $Param")
I see, though all your code will depend on your parse transform. Parse transforms can be hard to get correct, check out parse_trans (github.com/uwiger/parse_trans). io_lib with all those ~s helps with formatting, it separates the format from the data. The syntax you propose is "unusual" for Erlang code, but certainly readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.