当我实现下面的代码时,我得到了正确的日期:
10/05/2008
10/05/2009
当我使用printf
代替sprintf
时,我会得到以下内容:
10/05/200910/05/20081
1
关于为什么printf
打印尾随1
?
#!/usr/bin/perl
use strict; use warnings;
my ($from_date, $to_date) = to_from_dates();
print "$from_date\n";
print "$to_date\n";
sub to_from_dates {
my ($day, $month, $year) = (localtime)[3,4,5];
my $to_date = sprintf "%02d/%02d/%04d", $month+1, $day, $year+1900;
my $from_date = sprintf "%02d/%02d/%04d", $month+1, $day, $year+1899;
return ($from_date, $to_date);
}
答案 0 :(得分:13)
只有sprintf
返回可打印的值。 printf
打印值并返回1
以告诉您输出成功。
如果您只是从调用开头删除s
- es,那么您显示的输出正是我期望的输出。
sub to_from_dates {
my ($day, $month, $year) = (localtime)[3,4,5];
my $to_date=printf("%02d/%02d/%04d", $month+1, $day, $year+1900);
# printed: 10/05/2009 (no carriage return)
# $to_date = '1';
my $from_date=printf("%02d/%02d/%04d", $month+1, $day, $year+1899);
# printed: 10/05/2008 (no carriage return)
# $from_date = '1';
return ($from_date,$to_date);
}
($from_date,$to_date)=to_from_dates(); # returns ( 1, 1 )
# output: 10/05/200910/05/2008
print $from_date."\n"; # prints "1\n"; <- first line feed
# output: 10/05/200910/05/20081\n
print $to_date."\n"; # prints "1\n"; <- second line feed.
# output: 10/05/200910/05/20081\n1\n
答案 1 :(得分:5)
如果使用printf,Perl会打印该行并返回1的操作结果,然后打印出这个结果,这就是它们的来源。您可以执行printf
或print sprintf
答案 2 :(得分:3)