views:

187

answers:

3

When I implement the code below I get the correct dates:

10/05/2008
10/05/2009

When I use printf instead of sprintf, I get the following:

10/05/200910/05/20081
1

Any ideas on why printf prints the trailing 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);
}
+4  A: 

If you use printf, Perl prints the line and returns the result of the operation which is 1, then you print this result, this is where ones come from. You can do either printf or print sprintf

roddik
No, ***please*** don't do `printf sprintf`.
Sinan Ünür
+3  A: 

Well, sprintf returns a string, printf prints to a filehandle (STDOUT by default) and returns 1 if it was successful.

So when you use printf, both dates are being printed on the screen while executing to_from_dates and then print statements print result of to_from_dates which is always (1, 1) as both printf statements were successful.

vava
+11  A: 

Only sprintf returns a printable value. printf prints the value and returns 1 to tell you that output was a success.

The output you show is exactly the output I would expect if you were simply to erase the s-es from the beginning of the calls.

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
Axeman