【问题标题】:Achieving mixture of ~p and ~w formatting with io_lib:format使用 io_lib:format 实现 ~p 和 ~w 格式的混合
【发布时间】:2018-04-03 19:22:09
【问题描述】:

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

Format = "~p~n",
Data = {"ABC"},

出于特定目的,我想打印相同的输出,但只在一行上。我想实现与“~p”相同的格式(即Data 应该打印为{"ABC"} 而不是{[65,66,67]}。这可能吗?

我想我可以分三步完成:

  • io_lib:format~p
  • 遍历生成的字符串并删除所有新行字符
  • 正则表达式用单个空格替换多个连续空格的所有序列

但这种方法似乎乏味且效率低下。有没有更好的方法来使用 OTP 函数来做到这一点?

【问题讨论】:

    标签: erlang


    【解决方案1】:

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

    允许您声明行总长度(相对于每个元素)的替代方法是io_lib:print/4。我倾向于发现这个特定的功能对日志消息格式等更有用:

    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
    

    仔细阅读ioio_lib 的文档。实际上,其中包含很多不时弹出的功能。

    请记住,如果目标是控制终端本身,您还可以通过打印单个字符和使用 ASCII 控制序列来完成很多有趣的工作。如果您要解决的问题是构建基于文本的界面或类似的东西,则使用 io:put_chars/1 逐字符或逐位屏幕更新字符串输出可能是一个强大的工具。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-04
        • 2015-01-11
        • 2021-12-20
        • 1970-01-01
        • 2017-05-10
        • 2011-05-22
        相关资源
        最近更新 更多