On Thu, Mar 20, 2003 at 03:46:16PM -0800, R. Joseph Newton wrote: > "R. Joseph Newton" wrote:
[ Perl allows you to manipulate an object other than via its interface ] > > Without anything preventing me. I am not at all sure that this is a > > good thing. Is there any way to construct a class so that member > > data stays private? This was the factor that kept me from venturing > > into Perl OOP, and it still seems like it could lead to problems if > > the only thing preventing this kind of external access is the > > injuction "Don't do that!". > > Got it! The changes shown below seem to provide the protection I > want. I guess the object hash can be left as a programmer scratchpad, > while the payload remains protected as a private variable No. This will work fine if your class is a singleton, but every object will be accessing the same data. > > package Person; > > > > use strict; > > use warnings; > > use Address; > > > > my ($surname, $given_name, $address); This is class data. There is only one copy of these variables. Every object will access the same copy. > > sub new { > > my $self = {}; > > set_name(@_); > > bless $self; > > } > > > > sub set_name { > > my $self = shift; > > ($surname, $given_name) = @_; > > } > > > > sub print { > > my $self = shift; > > print "$surname, "; > > print "$given_name\n"; > > return unless defined $address; > > $address->print(); > > } > > > > sub set_address { > > my $self = shift; > > $address = Address::new(@_); > > } > > > > my $motto = "Every man, woman and child is a star"; > > __END__ Perl can do what you want, if you want to pay the price. If you use a closure as the object instead of a hash, you can ensure that everyone plays by whatever rules you dictate. For this, you pay the price of calling an extra function, plus whatever you do in it. In general though, Perl programmers are more pragmatic, and take the approach of documenting the interface and saying "if you don't use the API you're on your own". Having said that, Perl 6 will be providing the B&D features you are looking for. -- Paul Johnson - [EMAIL PROTECTED] http://www.pjcj.net -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]