Reputation: 1500
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";
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
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.
Upvotes: 1
Views: 1360
Reputation: 385655
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
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;
This could also be written as follows:
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;
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.)
Upvotes: 2