How can I modify a Perl DateTime object?
In my script I need to make a cycle like this one:
use DateTime;
for $j(0..3){
my ($date) = DateTi开发者_如何转开发me->now->ymd;
my ($k) = 0;
while($k <= $j){
$date = ($date->subtract( days => 7));
$k++;
}
print "$date\n";
}
which should get the current date, then one week ago, etc. Sadly, after getting the correct current date, it doesn't work and I don't know what's wrong.
Error message is "Can't call method "subtract" without a package or object reference [...]",
but I have no idea how to fix this.
If possible, I'd like to keep using DateTime only OR replacing it with another module (possibly no more than one).
Datetime->now->ymd
is a scalar (string, it appears), not an object/reference. You can't call subtract
on it because it doesn't exist. You'll probably just want to try omitting the ymd
part when you assign to $date
:
my ($date) = DateTime->now;
...
for(0..$j) {
$date = ($date->subtract( days => 7));
}
...
If you want to access the ymd
value, do it after you've created the object:
my ($date) = DateTime->now;
...
my ($ymd) = $date->ymd;
See the CPAN page for more.
If you tried using Data::Dumper on $date
you would immediately see what the problem is: $date
is a string, not an object. You should delay calling ymd()
on it until you need to stringify it.
use strict;
use warnings;
use DateTime;
for my $j (0..3)
{
my $date = DateTime->now;
$date = $date->subtract(days => 7) for (0 .. $j);
print $date->ymd, "\n";
}
PS. This code can be simplified even more by combining the loops:
my $date = DateTime->now;
for my $weeks (0..4)
{
print $date->ymd, "\n";
$date = $date->subtract(days => 7);
}
It's better to do the ymd when printing, after the calculations and working on the Date object.
See the difference when switching when ymd
and subtract
are called:
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
use DateTime;
sub main{
my $date = DateTime->now->subtract(days=>7)->ymd;
print "$date\n\n";
}
main();
精彩评论