Search code examples
perloop

How do I create a Perl class?


I am writing Perl classes to remove redundancies from scripts and since Perl has a lot of ways to make classes I keep having trouble making the classes properly. So does anyone have a best practice example of a class?

The biggest question I have is if there should be no global variables in a module how do you use variables across sub() in a module? Like Java self->foo = 10;

Basically just give me a class written in Java or C# or even C++ and write the same in Perl. Also extra points for showing how to do private, protected and public class variables properly. Inheritance and interfaces would be helpful to I guess.


Solution

  • a typical way of creating Perl objects is to 'bless' a hashref. The object instance can then store data against it's own set of hash keys.

    package SampleObject;
    
    use strict;
    use warnings;
    
    sub new {
        my ($class, %args) = @_;
        return bless { %args }, $class;
    }
    
    sub sample_method {
        my ($self) = @_;
        print $self->{sample_data};
    }
    

    and usage:

    my $obj = SampleObject->new( sample_data => 'hello world',
                                 more_data   => 'blah blah blah' );
    $obj->sample_method();
    

    Alternatively, accessor/mutator methods can be added (see Class::Accessor, Class::Accessor::Chained, etc for easy setting up of these) - these make it easier to validate data and add encapsulation (it's not enforced in Perl, you have to ensure your code doesn't go around an appropriate accessor/mutator and access the data in the blessed hashref directly).