如何在 Perl 中从 printf 渲染未定义的值?
我正在寻找一种优雅的方式来在通常呈现格式化数字的情况下表示未定义的值。 我将举一个小例子。 对于初学者来说,您当然不能使用这个:
#!/usr/bin/perl
use strict;
use warnings;
for my $s (1, 1.2, undef, 1.3) {
printf "%5.2f\n", $s;
}
...因为“使用警告”会在第三次迭代中告诉您“使用未初始化的值...”。 所以下一步是这样的:
#!/usr/bin/perl
use strict;
use warnings;
for my $s (1, 1.2, undef, 1.3) {
printf "%5.2f\n", $s//0;
}
顺便说一句,我喜欢新的 5.10 '//' 运算符吗? 但这也不是我想要的,因为 $s 的值不为零,它是未定义的。 我真正想要的是这样的:
#!/usr/bin/perl
use strict;
use warnings;
for my $s (1, 1.2, undef, 1.3) {
printf "%5.2f\n", $s//q();
}
...但我不能,因为这会在第三个值上产生“参数”不是数字...”问题。
这让我想到了我的问题。 我当然可以编写代码来检查我发出的每个数字的定义性,并创建一个完全不同的基于非 %f 的 printf 格式字符串,但是,好吧,...恶心。
有没有人定义了一种处理此类需求的好方法?
I'm looking for an elegant way to denote undefined values in situations where formatted numbers usually render. I'll work up a small example. For starters, you of course can't use this:
#!/usr/bin/perl
use strict;
use warnings;
for my $s (1, 1.2, undef, 1.3) {
printf "%5.2f\n", $s;
}
...because the 'use warnings' nails you with 'Use of uninitialized value...' on the third iteration. So the next step is something like this:
#!/usr/bin/perl
use strict;
use warnings;
for my $s (1, 1.2, undef, 1.3) {
printf "%5.2f\n", $s//0;
}
And, boy, do I like the new 5.10 '//' operator, by the way. But that's really not what I want, either, because the value of $s isn't zero, it's undefined. What I really want is something like this:
#!/usr/bin/perl
use strict;
use warnings;
for my $s (1, 1.2, undef, 1.3) {
printf "%5.2f\n", $s//q();
}
...but I can't because this generates the "Argument "" isn't numeric..." problem on the third value.
This brings me to the doorstep of my question. I can of course write code that checks every number I emit for defined-ness, and that creates a whole different non-%f-based printf format string, but, well, ...yuck.
Has anyone defined a nice way to deal with this type of requirement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为好的方法是编写/获取一个通用的漂亮打印机,它可以接受你扔给它的任何东西,然后执行以下操作:
I think the nice way is to write/get a generic prettyprinter that takes whatever you throw at it and then do:
我不认为这有什么恶心——这正是你想做的。
I don't think there's anything yuck about it -- it's exactly what you want to do.
这并不漂亮,但我只是这样做
It's not pretty, but I'd just do it as