On Fri, 30 Nov 2007 19:36:30 +0530, jagdish eashwar wrote
> Hi,
> 
> I came across some unexpected behaviour in datetime. In the following
> script, I first define $date1. Then I set $day1 = $date1. Then I add 
> 2 days to $day1. Why does $date1 also get incremented?
> 
> #!/usr/bin/perl
> use strict;
> use warnings;
> 
> use DateTime;
> 
> my $date1 = DateTime->new(year => 2007,
>              month => 12,
>              day => 23);
> 
> my $day1 = $date1;
> 
> $day1->add(days => 2);
> 
> print "day1 = ",$day1,"\n";   # gives me 2007-12-25 correctly.
> print "date1 = ",$date1,"\n";  # why does $date1 also change to 2007-
> 12-25?
> 
> Jagdish Eashwar

date1 is never a singular value like I think you are expecting. date1 points
to a datetime object, which is a collection of multiple values and the
functions to do work on those values. When you make day1 equal to date1 you
are actually pointing day1 at the same object, and therefore the same data. So
then when you change the underlying object by doing $day1>add(days=>2), they
both change.

You can always dump variables to see whats inside using Data::Dumper, like this:

#!/usr/bin/perl
use strict;
use warnings;

use DateTime;
use Data::Dumper;

my $date1 = DateTime->new(year => 2007,
             month => 12,
             day => 23);

print Dumper($date1);


This question is actually more perl related than DBI related. You might want
to try asking and searching at perlmonks.com before asking here next time -
you'll probably get a faster answer.

HTH,
Alex

Reply via email to