be12dune09a has asked for the wisdom of the Perl Monks concerning the following question:

How do I make a member of a class static in perl??Like in Java or C#.Can I or can I not do something like that???An exemple will be usefull.

Replies are listed 'Best First'.
Re: class static member
by derby (Abbot) on Nov 17, 2005 at 15:30 UTC
Re: class static member
by gaal (Parson) on Nov 17, 2005 at 15:35 UTC
    In Perl 5:

    package MyClass; our $total_objects; our $public_static_class_data; my $private_static_class_data; # For example: sub new { # ... $total_objects++; # ... }

    In Perl 6, the above would work if you replace package with class (though in general you don't write a new method yourself in Perl 6).

Re: class static member
by ikegami (Patriarch) on Nov 17, 2005 at 16:16 UTC

    There are two kinds of members: methods and attributes.

    Methods

    There is no difference between a static method and one that isn't in Perl, except how its called.

    package MyClass; sub method { my ($self, ...) = @_; ... } $obj->method(...);
    vs
    package MyClass; sub static_method { my ($class, ...) = @_; ... } MyClass->static_method(...);

    Attributes

    Static attributes are just package variables.

    package MyClass; our $static_attrib; $MyClass::static_attrib = 1; print($MyClass::static_attrib, "\n");