in reply to Something like c++'s static?

TheDamian discusses this in his book, Object Oriented Perl. In a nutshell, Perl has no equivalent to C++'s static (or Java's for that matter), but you can achieve roughly the same effect with properly scoped lexical variables:
use strict; my @foo; push @foo, Foo->new() for (0..4); package Foo; { my $count = 0; sub get_count { return $count } sub inc_count { return ++$count } } sub new { my $class = shift; $class->inc_count(); print STDERR 'there are ', $class->get_count(), " instances\n"; my $self = { bar => 42 }; return bless $self, $class; }
UPDATE:
Very good point perrin. Try adding the following code snippet in perrin's example and my example after the for loop line to see the difference in action:
print $Foo::count, "\n";
The methods get_count() and inc_count() are still accessible to the client in my code, by the way. That is not necessarily a good thing ...

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: (jeffa) Re: Something like c++'s static?
by perrin (Chancellor) on Aug 02, 2002 at 17:43 UTC
    Damian's example is fine if you need to hide all variables behind methods, but the use of closures often confuses newbies. The simple answer to this question is to just use a (package-scoped) global:
    use strict; my @foo; push @foo, Foo->new() for (0..4); package Foo; use vars qw($count); sub new { my $class = shift; $count++; print STDERR 'there are ', $count, " instances\n"; my $self = { bar => 42 }; return bless $self, $class; }
Re: (jeffa) Re: Something like c++'s static?
by mp (Deacon) on Aug 02, 2002 at 19:47 UTC