2014-03-13 45 views
2

刚刚更新了OP,因为我犯了一个错误的错字。为什么我不能减3次?

这个脚本

#!/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"; 

将输出

Can't use non Seconds object in operator overload at /usr/lib/perl/5.14/Time/Seconds.pm line 65. 

正确的答案是-0:09即。 0小时和9分钟。

问题

我怎么能减去3倍?
可以Time::PieceTime::Secondsint和模数我,所以我不必?

+4

'$ 3'和'$ t3'不是一回事。 – geoffspear

+0

非常好看,这解释了为什么我没有得到我想重现的原始错误。现在脚本产生“正确”的错误。 –

+0

是那些时间或持续时间?你想做什么(英文单词)? $ t2有时候总共有三个持续时间('$ t','$ t1'和'$ t3'),你试图获得第三个持续时间? – ikegami

回答

10

你不能从持续时间减去的时间。例如,九分钟减一点是毫无意义的。

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

现在您试图从该结果中减去$t3,即7:24am。但是7.25小时减去上午7:24是持续时间减去一天中的时间,并且不能完成。这就是为什么您会收到消息 Can't use non Seconds object,因为您正试图从Time::Seconds对象(持续时间)中减去Time::Piece对象(一天中的某个时间)。


更新

如果您在持续时间工作,那么你需要在整个这样的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"; 

输出

-9 

或者你更愿意从您的Time::Piece对象减去午夜00:00,这样

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; 

也输出。

注意,你不会得到你想要用的是什么模量在$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; 
} 

输出

-9 
+0

然后是否有一些简单的方法将'10:15''转换为'Time :: Seconds-> new(10 * 3600 + 15 * 60)'? – aschepler

+0

@aschepler:查看我的更新 – Borodin

+0

正在用夏令时班减去午夜是否正确?另外,如果我的脚本在午夜或几天之后运行,该怎么办? – aschepler

1

这句话:

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

应该

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

是的,我在脚本中做了一个错误的拼写错误,但是纠正后,我减去3次错误信息。 –

+1

'$ t2 - $ t1'是一个'Time :: Seconds'对象,你不能从中减去另一个'Time :: Piece'对象,所以你的回答并不回答OP的问题。 –

1

$t2 - $t1返回其上没有定义的-操作者Time::Seconds对象。

相关问题