premchai21 has asked for the wisdom of the Perl Monks concerning the following question: (object-oriented programming)

How can I create private object variables?

Originally posted as a Categorized Question.

  • Comment on How can I create private object variables?

Replies are listed 'Best First'.
Re: How can I create private object variables?
by jeffa (Bishop) on Mar 18, 2001 at 01:33 UTC

    Use closures. Check out perltoot for more info on how this code works.

    { package Foo; sub new { my $pkg = shift; my %data = ( bar => undef, ); bless sub { my $field = shift; @_ and $data{$field} = shift; $data{$field} }, $pkg } sub bar { my $self = shift; # the blessed closure $self->( 'bar', @_ ) } }
    And use:
    my $foo = new Foo; $foo->bar(42); # set it print $foo->bar; # get it
Re: How can I create private object variables?
by ton (Friar) on Apr 05, 2001 at 00:06 UTC
    ... but you usually don't need to. Since your source code is almost always accessible to the caller, s/he can easily modify it to read your members if s/he is determined. I prefer the more perl-y approach of indicating which variables are private via naming conventions (most people use a beginning underscore for private variables). This lets the user know that you make no guarentees about the existance of the member; e.g. the caller can access it if s/he wants to, but it might not be there in the next version. If their reliance on the existance of that member breaks their code later on, then it's their damn fault for accessing data that was not meant to be accessed. :)

    My $0.02

    Originally posted as a Categorized Answer.

Re: How can I create private object variables?
by pemungkah (Priest) on Nov 08, 2006 at 01:46 UTC

    Inside-out classes are another nice way to do this. The data is held in a my (lexical) variable inside the class; all the outside world sees is an anonymous scalar which is blessed into the class. The methods can access the class lexicals (as long as they're defined within scope of the lexicals), but the outside world can't.

    See Class::Std and Object::InsideOut for examples.