mbsheikh
mbsheikh

Reputation: 2521

Erlang string to atom and formatting a string

Using just list_to_atom() gives:

list_to_atom("hello"). 
hello
list_to_atom("Hello").
'Hello'

why the difference?

I am trying to format a string with numbers, strings and atoms as follows:

lists:flatten(io_lib:format("PUTVALUE ~p ~p", [list_to_atom("hello"), 40])).
"PUTVALUE hello 40"
lists:flatten(io_lib:format("PUTVALUE ~p ~p", [list_to_atom("Hello"), 40])).
"PUTVALUE 'Hello' 40"

what is the best way of doing this in Erlang?

Edit: To make the question clear, there are more values than the example above and in some cases the value can be a string or an atom, like

lists:flatten(io_lib:format("PUTVALUE ~p ~p ~p", [list_to_atom("hello"), X, 40])).

where the first parameter is always a string but X can either be an atom or a string. The third parameter is always a number.

Upvotes: 10

Views: 14087

Answers (4)

Lee
Lee

Reputation: 39

Erlang atoms always must start with a lower-case letter. That's why it is giving you a different result when you try to create an atom with the initial capital letter. It's creating an atom by adding the ' quotes because of the capital H.

Upvotes: -1

Odobenus Rosmarus
Odobenus Rosmarus

Reputation: 5998

You can use lists:concat for formatting such string

 lists:concat(["PUTVALUE ",hello," ",40]).

Upvotes: 6

shino
shino

Reputation: 849

If you want to get a flat list for strings and integers, using ~s and ~B may be straitforward:

lists:flatten(io_lib:format("PUTVALUE ~s ~B", ["Hello", 40])).  

Upvotes: 12

Fad
Fad

Reputation: 9858

In Erlang, an atom starts with a lowercase letter. For an atom to starts with an uppercase letter, it must be enclosed with single quotes.

http://www.erlang.org/doc/reference_manual/data_types.html#id66663

Upvotes: 13

Related Questions