如何在Perl中创建一个只读DateTime和DateTime::Duration



我有一个Perl脚本,试图将一些配置的DateTimeDateTime::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 "$an";
print "$bn";

在我的系统(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

所以看起来DateTimeDateTime::Duration Readonly导致它们的功能不正确。这是臭虫吗?还是我用错了Readonly ?我也尝试过Readonly::ScalarReadonly::Scalar1,两者的行为方式相同。

问题是它们是对象(引用),而不是普通的标量。您需要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 "$an"; # this isn't overloaded; you'll get "DateTime::Duration=HASH(...)"
print $a->days, "n";

相关内容

  • 没有找到相关文章

最新更新