为什么我有“在 printf 中缺少参数..."?在 perl 中? [英] Why am I having "Missing argument in printf at ..." in perl?

查看:166
本文介绍了为什么我有“在 printf 中缺少参数..."?在 perl 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有要打印到文件的 perl 代码.我给格式

I have perl code where am printing to file. I give the format

my $format = "%4d %2d %2d %2d %2d %2d" . " %7.2f" x 9 . "\n";

因为我正在写年月日时分秒和 9 个浮点值.然后我写到我的输出文件

because I am writing year month day hour minute second and 9 float values. Then I write to my output file as

printf $format, @data;        # print data on the screen
printf OUT $format, @data;    # print data into the file

上述两个语句都打印出来,但总是有一个警告在(行号)的 printf 中缺少参数".编写表单和/或 printf 的正确方法是什么.请帮忙.

Both of the above statements print, but always with a warning of "Missing argument in printf at (line number)". What is the correct way of writing the formt and/or the printf. Please help.

推荐答案

这表示格式字符串需要的值多于 @data 中包含的值.

This signifies that the format string requires more values than are contained in @data.

$ perl -we'my @data = qw( a b c ); printf "%s %s %s\n", @data;'
a b c

$ perl -we'my @data = qw( a b   ); printf "%s %s %s\n", @data;'
Missing argument in printf at -e line 1.
a b

在您的情况下,格式字符串有 15 个占位符,但 @data 包含的元素少于 15 个.

In your case, the format string has 15 placeholders, but @data contains fewer than 15 elements.

根据你的评论,我认为你想要

Based on your comments, I think you want

printf $format, $Y, $m, $d, $H, $M, $S, @data;

这也可以写成:

my $ts = sprintf("%04-%02d-%02d %02d:%02d:%02d", $Y, $m, $d, $H, $M, $S);
my $format = "%s".( " %7.2f" x 9 )."\n";
printf $format, $ts, @data;

大多数情况下,您将从纪元时间戳开始(由 time() 返回).在这种情况下,可以使用以下方法:

Most of time, you'll start with a epoch timestamp (as returned by time()). In that situation, one could use the following:

use POSIX qw( strftime );

my $ts = strftime("%Y-%m-%d %H:%M:%S", localtime(time()));
my $format = "%s".( " %7.2f" x 9 )."\n";
printf $format, $ts, @data;

(请注意,没有时区偏移的本地时间在回退"到夏令时区域的标准时间期间会产生不明确的时间戳.)

(Note that local times without an time zone offset creates ambiguous timestamps during "fall back" to standard time in areas with daylight-saving time.)

这篇关于为什么我有“在 printf 中缺少参数..."?在 perl 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆