go ahead... be a heretic | |
PerlMonks |
Re^5: Writing Modules/namespace polutionby Mugatu (Monk) |
on Mar 16, 2005 at 20:37 UTC ( [id://440135]=note: print w/replies, xml ) | Need Help?? |
Is there a way of privatizing variables/member functions of a package The only way I know of is through lexical variables. You can use them to create closures that only the enclosed blocks have access to. There are ways to get around this protection, but they're not pretty or for the faint of heart. Here's the basic example:
You could use that package like so:
Using anonymous coderefs, you can get the same protection for subroutines:
Now, a problem comes in when you want to use these techniques with objects. Converted to an object interface, these lexical variables would be persistent across all instances of the object. Trying to use them for instance data would obviously be a problem. Thus, you have to keep track of the instances yourself. One way to do this is to make each data member a hash that is keyed on the object instance's reference ID. You have to be careful to remove these instance variables when the object is destroyed, though, because the hash is persistent throughout the program's lifetime. Note, this is an approach that Abigail-II developed, called inside-out objects. Here's a very minimal example:
Of course, it's neat that you can get this protection if you really need it. But most of the time, my experience shows that you don't really need it. Most of the community simply relies on politeness and common conventions, such as using _ in the beginning of private method names.
In Section
Seekers of Perl Wisdom
|
|