如何在 Perl printf 表达式中包含变量?
如何在 printf 表达式中包含变量?
这是我的示例:
printf "%${cols}s", $_;
其中 $cols
是列数 $_
是一个字符串。
该语句会导致“无效转换”警告。
问题最终是我忘记了删除变量。嘎。谢谢大家。
How can I include a variable in a printf expression?
Here's my example:
printf "%${cols}s", $_;
Where $cols
is the number of columns
and $_
is a string.
The statement results in an "Invalid conversion" warning.
The problem ended up being that I forgot to chomp the variable. Gah. Thanks everyone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我无法重现你的问题。以下代码工作正常:
它使用至少 40 列宽度打印任何输入行。
I cannot reproduce your problem. The following code works fine:
It prints any input line using at least 40 columns of width.
您的插值变量
$cols
看起来应该是一个数字,比如 10,所以应该插值并相当于
有效的格式字符串。
但是,如果
$cols
不是数字或有效格式字符串,您会收到警告。例如,如果:
这将导致
"%ws"
作为格式字符串 - 给出您引用的错误:可以找到有效的格式信息此处。
Your interpolated variable
$cols
looks like its supposed to be a number, say 10, soshould interpolate and be equivalent to
which is a valid format string.
If however
$cols
was something other than a number or valid format string, you'd get the warning.For example, if:
that would result in
"%ws"
as a format string - giving the error you quote:Valid format information can be found here.
我弄清楚了你的具体问题。你的代码是正确的。但是,我认为
$cols
可能是从用户输入中读取的数字,如下所示:这有效,并且在数字上下文中
$cols
将显示为一个数字,但是问题是$cols
没有出现在此处的数字上下文中。它位于字符串上下文中,这意味着您的格式字符串不会扩展为"%5s"
,而是扩展为"%5\ns"
。那里的换行符弄乱了格式字符串。将您读取
$cols
的代码更改为:请参阅 < 上的文档code>chomp,因为您可能也想将它用于其他输入读取。
I figured out your specific problem. Your code is correct. However, I suppose
$cols
might be a number read from user input, say like this:This works, and in numeric context
$cols
will appear to be a number, but the problem is that$cols
isn't appearing in numeric context here. It's in string context, which means that instead of expanding to"%5s"
, your format string expands to"%5\ns"
. The newline there is mucking up the format string.Change the code where you read
$cols
to this:See the documentation on
chomp
, as you may want to use it for other input reading as well.始终在格式说明符中使用
*
来明确指示可变宽度!这类似于使用printf "%s", $str
而不是printf $str
的建议。来自 关于
sprintf
的 perlfunc 文档:例如:
输出:
启用
warnings
编译指示后,您将看到非数字宽度参数的警告。Always use
*
in your format specifier to unambiguously indicate variable width! This is similar to the advice to useprintf "%s", $str
rather thanprintf $str
.From the perlfunc documentation on
sprintf
:For example:
Output:
With the
warnings
pragma enabled, you'll see warnings for non-numeric width arguments.您当前的方法应该有效
Your current method should work
以下似乎对我有用
:
The following seems to work for me:
yields