10.5 Using Class VariablesWhat if you want to iterate over all the animals we've made so far? Animals may exist all over the program namespace and are lost once they're handed back from the named constructor method.However, you can record the created animal in a hash and iterate over that hash. The key to the hash can be the stringified form of the animal reference,[9] while the value can be the actual reference, allowing you to access its name or class.[9] Or any other convenient and unique string. For example, let's extend named as follows: ## in Animal The uppercase name for %REGISTRY is a reminder that this variable is more global than most variables. In this case, it's a metavariable that contains information about many instances.Note that when used as a key, $self stringifies, which means it turns into a string unique to the object.We also need to add a new method: sub registered {Now you can see all the animals we've made: my @cows = map Cow->named($_), qw(Bessie Gwen); This prints: We've seen: Note that the animals die at their proper time because the variables holding the animals are all being destroyed at the final step. Or are they? |
•
Table of Contents
•
Index
•
Reviews
•
Reader Reviews
•
Errata
Learning Perl Objects, References & Modules
By
Randal L. Schwartz