我有一个Perl脚本试图将一些已配置的DateTime
和DateTime::Duration
个实例设置为Readonly
个常量。但是,如果它们是Readonly
,我会在尝试对这些对象进行数学运算时看到奇怪的行为。这是一个最小的例子:
#!/usr/bin/perl -w
use strict;
use warnings;
use DateTime;
use Readonly;
Readonly my $X => DateTime->now;
my $x = DateTime->now;
Readonly my $Y => DateTime::Duration->new( days => 3 );
my $y = DateTime::Duration->new( days => 3 );
my $a = $X - $Y;
my $b = $x - $y;
print "$a\n";
print "$b\n";
在我的系统上(OSX上的Perl 5.10.0)显示:
$ ./datetime_test.pl
Argument "2011-07-12T20:36:08" isn't numeric in subtraction (-) at ./datetime_test.pl line 15.
-4305941629
2011-07-09T20:36:08
所以看起来好像使DateTime
和DateTime::Duration
Readonly
导致它们无法正常运行。这是一个错误吗?或者我使用Readonly
错了?我也尝试了Readonly::Scalar
和Readonly::Scalar1
,两者的行为方式相同。
答案 0 :(得分:5)
问题在于它们是对象(引用),而不是普通的标量。您需要Readonly
引用中包含的值,而不是引用本身;但事实证明这很棘手。这样的事情似乎有效:
use Readonly;
use DateTime;
# you can't just say "Readonly %$dt"; here at least, it dies on blessed refs
sub makeRO {
my $dt = shift;
while (my ($k, $v) = each %$dt) {
Readonly $dt->{$k} => $v;
}
}
my $x = DateTime::Duration->new(days => 3);
makeRO($x);
my $y = DateTime::Duration->new(days => 3);
my $a = $x - $y;
# print "$a\n"; # this isn't overloaded; you'll get "DateTime::Duration=HASH(...)"
print $a->days, "\n";