in reply to Still not getting it: hashref OO class variables
A better solution to that issue is to define a new collection class that holds these counters, and global information. As new objects are created, they should be added to an instance of the collection class - or better, use a method in the collection class to create instances of the sub-objects - that way you can manage them collectively.
That said, here is updated code for your Shoe.pm that ignores the advice above, but allows you to implement the Boot class without any methods (disable the current methods).
### In Shoe.pm package Shoe; use strict; use warnings; # Shoes with holes in their soles. my %num_holey; sub new { my $class = shift; my $self = {}; # ... bless $self, $class; return $self; } # Instance method that happens to access a class variable. sub wear_out_sole { my $self = shift; $self->incr_num_holey() ; #$num_holey++; print "Sole on this " . ref($self) . " has been worn out.\n"; $self->how_many_holey(); } # Class methods. sub how_many_holey { my $self = shift; local $_; print "Currently, there are $num_holey{$_} holey " . "$_(s).\n" for keys %num_holey; } sub incr_num_holey { my $self = shift; $num_holey{ref($self)}++; } 1;
#!/usr/bin/env perl use strict; use warnings; use Shoe; use Boot; {package Shoe_Rack; sub new{ my $class = shift; my $self = {}; # ... bless $self, $class; return $self; } sub Buy{ my $self = shift; my $TypeToBuy = shift or die "What type to buy ?\n"; $self->{COUNT}{$TypeToBuy}++; # Count whatever we buy my $newthing = $TypeToBuy->new(); push @{$self->{COLLECTION}}, $newthing; return $newthing; } sub getcollection{ my $self = shift; return @{$self->{COLLECTION}}; } 1; } my $s = Shoe->new(); $s->wear_out_sole(); my $b = Boot->new(); $b->wear_out_sole(); my $b2 = Boot->new(); $b2->wear_out_sole(); my $Rack = new Shoe_Rack; my $s1 =$Rack->Buy("Shoe"); $Rack->Buy("Shoe"); $Rack->Buy("Boot"); $Rack->Buy("Boot"); $Rack->Buy("Shoe"); $_->wear_out_sole() for $Rack->getcollection();
"As you get older three things happen. The first is your memory goes, and I can't remember the other two... " - Sir Norman Wisdom
|
|---|