在Perl中,如何使用sprintf将零填充到可变长度? [英] How do I use sprintf to zero fill to a variable length in Perl?
问题描述
我想使用Perl的 sprintf 来对变量进行零填充.
I want to use Perl's sprintf to zerofill a variable.
sprintf("%08d", $var);
但是我想动态确定要填零的位数.
But I want to dynamically determine how many digits to zerofill.
如何用名为$zerofill
的变量替换sprintf("%08d", $var)
中的"8"?
How do I replace the "8" in sprintf("%08d", $var)
with a variable called $zerofill
?
推荐答案
sprintf的第一个参数只是一个字符串:
my $zerofill = 9;
my $number = 1000;
my $filled = sprintf "%0${zerofill}d", $number;
请注意用大括号将变量名与字符串的其余部分区分开.
Notice the braces to set apart the variable name from the rest of the string.
在学习Perl 时,我们会遇到一个特殊的问题,即提醒人们该字符串是只是字符串. :)
We have this particular problem as a slightly clever exercise in Learning Perl to remind people that strings are just strings. :)
However, as mobrule points out in his answer, sprintf has many features to give you this sort of flexibility. The documentation for such a seemingly simple function is quite long and there are a lot of goodies in it.
这篇关于在Perl中,如何使用sprintf将零填充到可变长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!