Erlang 实现~p和~w格式与io_lib:format的混合

Erlang 实现~p和~w格式与io_lib:format的混合,erlang,Erlang,假设我有一个任意格式的字符串和som对应的数据,数据包含带有字符串元素的元组。作为一个(缩短的)示例: 出于特定目的,我希望打印相同的输出,但只打印一行。我希望实现与“~p”相同的格式设置(即,数据应打印为{“ABC”}而不是{[65,66,67]}。这可能吗 我想我可以分三步来做: io_lib:formatwith~p 循环遍历结果字符串并删除所有新行字符 正则表达式将多个连续空间的所有序列替换为单个空间 但是这种方法似乎冗长且效率低下。有没有更好的方法来使用OTP函数来实现这一点?如果

假设我有一个任意格式的字符串和som对应的数据,数据包含带有字符串元素的元组。作为一个(缩短的)示例:

出于特定目的,我希望打印相同的输出,但只打印一行。我希望实现与“~p”相同的格式设置(即,
数据
应打印为
{“ABC”}
而不是
{[65,66,67]}
。这可能吗

我想我可以分三步来做:

  • io_lib:format
    with
    ~p
  • 循环遍历结果字符串并删除所有新行字符
  • 正则表达式将多个连续空间的所有序列替换为单个空间

但是这种方法似乎冗长且效率低下。有没有更好的方法来使用OTP函数来实现这一点?

如果您知道输出的宽度永远不会超过(比如)一百万个字符,则可以指定
~p
说明符的输出宽度:

io:format("~1000000p", [Data]).

正如Legosca所指出的,
io:format/2
试图在漂亮的打印元素和行长度等方面保持礼貌,您可以通过格式字符串参数对每个元素进行调整。请注意,这意味着如果使用格式控制序列,格式本身就是控制每个元素输出长度的地方

允许您声明行的总长度(相对于每个元素)的另一种方法是。我倾向于发现此特定函数对于日志消息格式设置更有用:

1> T = {"Some really long things","are in this tuple","but it won't really matter","because they will be in line"}.
{"Some really long things","are in this tuple",
 "but it won't really matter","because they will be in line"}
2> io:format("~tp~n", [T]).
{"Some really long things","are in this tuple","but it won't really matter",
 "because they will be in line"}
3> S = io_lib:print(T, 1, 1000, -1).
[123,
 ["\"Some really long things\"",44,"\"are in this tuple\"",
  44,"\"but it won't really matter\"",44,
  "\"because they will be in line\""],
 125]
4> lists:flatten(S).
"{\"Some really long things\",\"are in this tuple\",\"but it won't really matter\",\"because they will be in line\"}"
5> io:format("~ts~n", [S]).
{"Some really long things","are in this tuple","but it won't really matter","because they will be in line"}
ok
仔细阅读文档,了解更多信息。实际上,文档中包含了很多不时弹出的功能

请记住,如果目标是控制终端本身,您还可以通过打印单个字符和使用ASCII控制序列来完成大量有趣的工作。如果您要解决的问题是构建基于文本的接口或som,则使用逐字符或逐blit屏幕更新字符串输出是一个强大的工具这是相似的

1> T = {"Some really long things","are in this tuple","but it won't really matter","because they will be in line"}.
{"Some really long things","are in this tuple",
 "but it won't really matter","because they will be in line"}
2> io:format("~tp~n", [T]).
{"Some really long things","are in this tuple","but it won't really matter",
 "because they will be in line"}
3> S = io_lib:print(T, 1, 1000, -1).
[123,
 ["\"Some really long things\"",44,"\"are in this tuple\"",
  44,"\"but it won't really matter\"",44,
  "\"because they will be in line\""],
 125]
4> lists:flatten(S).
"{\"Some really long things\",\"are in this tuple\",\"but it won't really matter\",\"because they will be in line\"}"
5> io:format("~ts~n", [S]).
{"Some really long things","are in this tuple","but it won't really matter","because they will be in line"}
ok