views:

91

answers:

3

In my script I need to make a cycle like this one:

use DateTime;
for $j(0..3){
    my ($date) = DateTime->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).

+8  A: 

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.

eldarerathis
Yep, I messed that up. =) Thanks
Gurzo
+6  A: 

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);    
}
Ether
Is it just this week, or has there been a steady acculumation of questions by people who don't even bother to inspect values or try anything to debug their problems? It seems really odd to me because in most cases, the level of skill of the questioner seems to indicate they should know this stuff.
brian d foy
@brian: there does seem to be a bit of an uptick lately. I wonder if it is to do with the new school year starting (in the northern hemisphere).
Ether
+3  A: 

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();
vol7ron