Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Perl class?

Tags:

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.

like image 598
kthakore Avatar asked Jun 24 '09 09:06

kthakore


People also ask

How do you create a object in Perl?

To create an instance of a class (an object) we need an object constructor. This constructor is a method defined within the package. Most programmers choose to name this object constructor method new, but in Perl you can use any name. You can use any kind of Perl variable as an object in Perl.

What does @_ mean in Perl?

Using the Parameter Array (@_) Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order.

What is constructor in Perl?

The constructor method is a Perl subroutine that returns an object which is an instance of the class. It is convention to name the constructor method 'new', but it can be any valid subroutine name. The constructor method works by using the bless function on a hash reference and the class name (the package name).

Does Perl have OOP?

Summary: in this tutorial, you will learn about Perl Object-Oriented Programming or Perl OOP. You will learn how to create a simple Perl class and use it in other programs. Besides procedural programming, Perl also provides you with object-orient programming paradigm.


4 Answers

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).

like image 166
plusplus Avatar answered Sep 25 '22 06:09

plusplus


Well, the Perl is easy, but I am rusty in the other languages, so I will update with them in a bit. Here is a plain Perl class:

#!/usr/bin/perl

package Person;

use strict;
use warnings;
use Carp;

sub new {
    my $class = shift;
    my $self  = { @_ };
    croak "bad arguments" unless defined $self->{firstname} and defined $self->{lastname}; 
    return bless $self, $class; #this is what makes a reference into an object
}

sub name {
    my $self = shift;
    return "$self->{firstname} $self->{lastname}";
}

#and here is some code that uses it
package main;

my $person = Person->new(firstname => "Chas.", lastname => "Owens");
print $person->name, "\n";

Here is the same class written using the new Moose style objects:

#!/usr/bin/perl

package Person;

use Moose; #does use strict; use warnings; for you

has firstname => ( is => 'rw', isa => 'Str', required => 1 );
has lastname  => ( is => 'rw', isa => 'Str', required => 1 );

sub name {
    my $self = shift;
    return $self->firstname . " " . $self->lastname;
}

#and here is some code that uses it
package main;

my $person = Person->new(firstname => "Chas.", lastname => "Owens");
print $person->name, "\n";

And MooseX::Declare removes the need for even more code and makes things look nice:

#!/usr/bin/perl

use MooseX::Declare;

class Person {
    has firstname => ( is => 'rw', isa => 'Str', required => 1 );
    has lastname  => ( is => 'rw', isa => 'Str', required => 1 );

    method name {
            return $self->firstname . " " . $self->lastname;
    }
}

#and here is some code that uses it
package main;

my $person = Person->new(firstname => "Chas.", lastname => "Owens");
print $person->name, "\n";

A quick note, These two class are the first two Moose classes I have ever written. And here is some very rusty C++ code (don't cut yourself on it or you will need a tetanus shot):

#include <stdio.h>
#include <string.h>

class Person {
    char* firstname;
    char* lastname;

    public:
    Person(char* first, char* last) {
        firstname = first;
        lastname  = last;
    }

    char* name(void) {
        int len = strlen(firstname) + strlen(lastname) + 1;
        char* name = new char[len];
        name[0] = '\0';
        strcat(name, firstname);
        strcat(name, " ");
        strcat(name, lastname);
        return name;
    }
};

int main(void) {
    Person* p    = new Person("Chas.", "Owens");
    char*   name = p->name();
    printf("%s\n", name);
    delete name;
    delete p;
    return 0;
}
like image 25
Chas. Owens Avatar answered Sep 22 '22 06:09

Chas. Owens


Check out Moose, which is an extension of the Perl 5 object system.

The following will help you in learning Moose:

  • Moose::Manual
  • Moose::Cookbook
like image 23
Alan Haggai Alavi Avatar answered Sep 26 '22 06:09

Alan Haggai Alavi


Besides Moose, which people have already mentioned...

If you are just talking about classes (so, not objects), you typically create class data with lexical variables scoped to the file and use one class per file. You create accessor methods to deal with them. There are various ways you can deal with that.

However, it sounds like you need to start with something like Intermediate Perl or Damian Conway's Object Oriented Perl. There's too much to explain for anyone to take the time to reproduce all of that in a Stackoverflow answer.

like image 22
brian d foy Avatar answered Sep 25 '22 06:09

brian d foy