Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Answer: How can I create private object variables?

by jeffa (Bishop)
on Mar 18, 2001 at 01:33 UTC ( #65201=categorized answer: print w/replies, xml ) Need Help??

Q&A > object-oriented programming > How can I create private object variables? - Answer contributed by jeffa

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

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2016-09-28 20:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:







    Results (540 votes). Check out past polls.