开发者

How to format a flat string with integers in it in erlang?

In erlang, I want to format a string with integers in it and I want the result to be flattened. But I get this:

io_lib:format("sdfsdf ~B", [12312]).                 
[115,100,102,115,100,102,32,"12312"]

I can get the desired result by using the code below but it is really not elegant.

lists:flatten(io_lib:format开发者_如何学Python("sdfsdf ~B", [12312])).
"sdfsdf 12312"

Is there a better formatting strings with integers in them, so that they are flat? Ideally, using only one function?


You flatten a list using lists:flatten/1 as you've done in your example.

If you can accept a binary, list_to_binary/1 is quite efficient:

1> list_to_binary(io_lib:format("sdfsdf ~B", [12312])).
<<"sdfsdf 12312">>

However, question why you need a flat list in the first place. If it is just cosmetics, you don't need it. io:format/1,2,3 and most other port functions (gen_tcp etc) accept so called deep IO lists (nested lists with characters and binaries):

2> io:format([115,100,102,115,100,102,32,"12312"]).
sdfsdf 12312ok


There is an efficiency reason that io_lib:format returns deep lists. Basically it saves a call to lists:flatten.

Ask yourself why you want the list flattened. If you are going to print the list or send it to a port or write it to a file, all those operations handle deep lists.

If you really need a flattened list for some reason, then just flatten it. Or you can create your own my_io_lib:format that returns flattened lists if you think it important.

(If you only want to flatten the list for debugging reasons then either print your strings with ~s, or create a flattener in an erlang module named user_default. Something like this:

 -module(user_default).
 -compile(export_all).
 %% either this:
 fl(String) ->
    lists:flatten(String).
 %% or this:
 pp(String) ->
     io:format("~s~n", [String]).

Then you can use fl/1 and print/1 in the Erlang shell (as long as user_default.beam is in your path of course).)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜