7

我正在解析一些数据并组织它,现在我需要在一个变量中捕获它。

在此之前我从未使用过 printf 或 sprintf 。

我以这样的方式使用 printf 来组织数据:

printf("%-30s %18s %18s\n", "$a", "$b", "$c\n");

现在我有一个存储字符串的变量,我想将组织好的数据附加到变量 $result。

我尝试了类似的东西

$result.printf("%-30s %18s %18s\n", "$a", "$b", "$c\n");

它不起作用。我也试过 sprintf。

有任何想法吗?

谢谢,

4

2 回答 2

10

printf将构造的字符串输出到指定的句柄(如果省略,则为当前默认值)并返回一个布尔值,指示是否发生 IO 错误。没用。sprintf返回构造的字符串,所以你想要这个。

要连接两个字符串(将一个附加到另一个),一个使用.运算符 (or join)

$result . sprintf(...)

但是你说这行不通。大概是因为您还想将生成的字符串存储在 中$result,您可以使用

$result = $result . sprintf(...);

或更短的

$result .= sprintf(...);
于 2013-03-18T23:44:17.340 回答
2

Don't know what you mean by "tried sprintf too", because there's no reason it would not work if you do it right. Although that syntax you showed does not look much like perl, more like python or ruby?

my $foo = sprintf("%-30s %18s %18s\n", "$a", "$b", "$c\n");
$result .= $foo;
于 2013-03-18T22:27:59.290 回答