【问题标题】:How to add new lines to stdout in perl如何在 perl 中向标准输出添加新行
【发布时间】:2020-01-03 18:24:42
【问题描述】:

我在 .cgi 文件的末尾有这段代码:

if ($cmd eq 'set'){
         my @args = ('ranking', 'set', $bug_id, $rank);
         system(@args) == 0
           or die "system @args failed: $?";
 }

您可以输入数据并将其解释为系统命令。 HTML 页面上的示例输出如下:

Current ranking is 1, I will decrement all bugs with higher ranking by one Not shifting any bug, since there is another one with ranking Bug 111 removed from ranking Bug 111 inserted into ranking at position 1

(全部在一行中)

但我需要像这样格式化输出:

Current ranking is 1,
I will decrement all bugs with higher ranking by one
Not shifting any bug, since there is another one with ranking
Bug 111 removed from ranking
Bug 111 inserted into ranking at position 1

如何将这些新行添加到 HTML 页面?

【问题讨论】:

  • 什么打印 HTML 输出?系统?
  • 上面的代码打印输出。
  • 您似乎对标准文本输出和 HTML 感到困惑。在将输出发送到 HTML 文档之前,尝试通过第二个 perl 单行:| perl -pe 's/$/<br>/' 将上面的代码输出管道化。
  • HTML 嵌入在 .cgi 文件中。在上面的coden-p之后只有一个print "</body>";,那么| perl -pe 's/$/<br>/'应该放在哪里呢?
  • 嗯,另一种解决方案是“捕获”并按摩ranking 命令的输出,正如@DavidO 所建议的那样。稍后我会将建议的代码放入下面的答案中。

标签: html perl cgi


【解决方案1】:

用 Perl 中的反引号运算符替换 system 调用以将您的输出捕获到一个变量中,然后在打印之前对输出进行处理:

if ($cmd eq 'set'){
         $_ = `ranking set $bug_id $rank`;
         $? == 0
           or die "command 'ranking set $bug_id $rank' failed: $?";
         s/$/<br>/mg;
         print;
 }

需要s/ 上的/m,以便将文本视为m多行($ 匹配\n)。 /g 表示“执行所有事件”(所有行)。

也许这对你有用。 (警告:未经测试。)

【讨论】:

  • 您可以只使用s/\n/&lt;br&gt;/g 而不使用/m
  • 是的。我想保留\ns 以提高可读性,所以建议s/\n/&lt;br&gt;\n/g。 ($匹配 \n,它在\n 之前零匹配。)
  • 注入错误!! &amp;&lt; 也应该转义
猜你喜欢
  • 1970-01-01
  • 2021-07-22
  • 2012-03-16
  • 2018-07-20
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 2013-08-20
  • 2022-01-25
相关资源
最近更新 更多