The project I'm working on generates an HTML-formatted monthly calendar (and before anyone suggests HTML::CalendarMonth on CPAN I've already looked at it... it's WAY more heavy weight than I need. My module is an order of magnitude smaller.) I wanted to give the user the ability to pass HTML formatting to individual table cells (make the cell for February 6th red, for example) so my first attempt was this:
...where $format is a reference to a hash. (This way I get to pass HTML formatting directly to the HTML output functions in CGI.pm.) This works all fine and dandy, but since I'm doing straight assignment whatever formatting that's passed in completely replaces whatever formatting was there, so that if the formatting originally was {align => "left"} it gets clobbered when you pass {bgcolor => "red"}.sub format_cell { my ($self, $format, @days) = @_; # @days lets you apply formatting to more # than one date at a time. foreach (@days) { $self->{'cell_format'}[$_] = $format; } }
The answer is just to assign only to the keys I need instead of clobbering the whole hash, so here's try #2:
Same as before, only now I'm just referencing the hash keys passed, and only the ones passed change values in my object. I thought certainly this would work.sub format_cell2 { my ($self, $format, @days) = @_; foreach (@days) { foreach my $key (keys %$format) { ${$self->{'cell_format'}[$_]}{$key} = + ${$format}{$key}; } } }
The problem is that whenever this method is called on a single object it changes ALL the values on ALL the days, and, as a particularly weird bonus, it changes it on EVERY object created with the module. (One object is created for each month... I have a program creating, say, 6 months at a time.)
Here's an actual example of how I call the method:
...where $html_months{$key} contains an object for some month. The idea is that the cell for the 15th of that month should now be red, but in reality, ALL cells become red, on ALL objects in %html_months. This happens even if the method is called prior to the creation of the other objects.$html_months{$key} -> format_cell2({bgcolor => "red"}, 15)
I have a theory that I have somehow called a Class method, which would explain the universality of my problem, but in my debugging I've verified that it's only being called against a single object, and only one time.
Sigh... sorry for this being so long, but I really have no idea what to do. Any help from any OO Monks out there would be appreciated.
Gary Blackburn
Trained Killer
In reply to Strange method behavior by Trimbach
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |