Why do I get the final "1" after printf exits in Perl?

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

10/05/2008
10/05/2009

When I use printfinstead sprintf, I get the following:

10/05/200910/05/20081
1

Any ideas on why the printffinal prints 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);
}
+3
source share
3 answers

Only sprintfreturns the value to print. printfprints a value and returns 1to inform you that the result was successful.

The output you are showing is exactly the result that I would expect if you just erased s-es from the start 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
+13
source

printf, Perl , 1, , . printf, print sprintf

+5

Well, it sprintfreturns a string, printfprints to the file descriptor ( STDOUT) by default, and returns 1if it was successful.

Therefore, when you use printf, both dates are printed on the screen at runtime to_from_dates, and then the printoperators print the result to_from_dates, which is always (1, 1), as both operators printfwere successful.

+3
source

Source: https://habr.com/ru/post/1719290/


All Articles