为什么我不能减3次?

Jas*_*nes 2 perl time

刚刚更新OP,因为我做了一个糟糕的错字.

这个脚本

#!/usr/bin/perl
use warnings;
use strict;
use Time::Piece;

my $t1 = Time::Piece->strptime( '10:15', '%H:%M' );
my $t2 = Time::Piece->strptime( '17:30', '%H:%M' );
my $t3 = Time::Piece->strptime( '7:24', '%H:%M' );

my $t = $t2 - $t1 - $t3;

print int($t->hours) . ":" . $t->minutes%60 . "\n";
Run Code Online (Sandbox Code Playgroud)

将输出

Can't use non Seconds object in operator overload at /usr/lib/perl/5.14/Time/Seconds.pm line 65.
Run Code Online (Sandbox Code Playgroud)

正确的答案是-0:09.0小时和-9分钟.

我该如何减去3次?
可以Time::Piece或为我Time::Secondsint模数,所以我没有?

Bor*_*din 10

您无法从持续时间中减去时间.例如,九分钟减去一点毫无意义.

在这里你有$t1等于10:15am,$t2等于17:305:30pm.所以$t2 - $t1是他们,或7.25小时之间的时间.

现在,你想减$t3,这是7:24am,从这一结果.但是7.25小时减去7:24 am是持续时间减去一天中的时间,并且无法完成.这就是为什么你得到消息, Can't use non Seconds object因为你试图Time::Piece从一个Time::Seconds对象(一个持续时间)中减去一个对象(一天中的某个时间).


更新

如果你在持续时间工作,那么你需要Time::Seconds像这样的模块.

use strict;
use warnings;

use Time::Seconds;

my $t1 = Time::Seconds->new(10 * ONE_HOUR + 15 * ONE_MINUTE); # 10:15
my $t2 = Time::Seconds->new(17 * ONE_HOUR + 30 * ONE_MINUTE); # 17:30
my $t3 = Time::Seconds->new( 7 * ONE_HOUR + 24 * ONE_MINUTE); #  7:24

my $t = $t2 - $t1 - $t3;

print $t->minutes, "\n";
Run Code Online (Sandbox Code Playgroud)

产量

-9
Run Code Online (Sandbox Code Playgroud)

或者你可能希望00:00从你的Time::Piece物体中减去午夜,就像这样

use strict;
use warnings;

use Time::Piece;

use constant MIDNIGHT => Time::Piece->strptime('00:00', '%H:%M');

my $t1 = Time::Piece->strptime( '10:15', '%H:%M' );
my $t2 = Time::Piece->strptime( '17:30', '%H:%M' );
my $t3 = Time::Piece->strptime(  '7:24', '%H:%M' );

$_ -= MIDNIGHT for $t1, $t2, $t3;

my $t = $t2 - $t1 - $t3;

print $t->minutes;
Run Code Online (Sandbox Code Playgroud)

这也是输出-9.

请注意,使用模数不能得到你想要的$t->minutes % 60因为-9 % 6051分钟.


更新2

另一个选择是编写一个使用前面任一选项的辅助例程.此示例具有子例程new_duration,该子例程Time::Piece->strptime用于解析传入的字符串,然后在返回结果Time::Seconds对象之前减去午夜.

use strict;
use warnings;

use Time::Piece;
use Time::Seconds;

use constant MIDNIGHT => Time::Piece->strptime('00:00', '%H:%M');

my $t1 = new_duration('10:15');
my $t2 = new_duration('17:30');
my $t3 = new_duration( '7:24');

my $t = $t2 - $t1 - $t3;

print $t->minutes;

sub new_duration {
  Time::Piece->strptime(shift, '%H:%M') - MIDNIGHT;
}
Run Code Online (Sandbox Code Playgroud)

产量

-9
Run Code Online (Sandbox Code Playgroud)