tags:

views:

855

answers:

8

Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties?

A: 

Here's a guide: http://www.tutorialspoint.com/perl/perl_oo_perl.htm

Edit: Good point, I'm removing the copied code.

pix0r
+2  A: 

The official tutorial on the CPAN site is good.

There's also a good article called Camel POOP at CodeProject.

Bruce Alderman
Note that all the perldoc tutorials are also available at the commandline, if you have a normal Perl installation: perldoc perltoot for this one. (See also perldoc perlboot for more fun with objects in Perl.)
Telemachus
+20  A: 

You should definitely take a look at Moose.

package Point;
use Moose; # automatically turns on strict and warnings

has 'x' => (is => 'rw', isa => 'Int');
has 'y' => (is => 'rw', isa => 'Int');

sub clear {
    my $self = shift;
    $self->x(0);
    $self->y(0);
}

Moose gives you (among other things) a constructor, accessor methods, and type checking for free!

So in your code you can:

my $p = Point->new({x=>10 , y=>20}); # Free constructor
$p->x(15);     # Free setter
print $p->x(); # Free getter
$p->clear();
$p->x(15.5);   # FAILS! Free type check.

A good starting point is Moose::Manual and Moose::Cookbook

If you just need the basic stuff you can also use Mouse which is not as complete, but without most of the compile time penalty.

Pat
or Mouse if you need just simple features of Moose
Alexandr Ciornii
is there any good tutorial for totally newbies on Moose? thanks
melaos
@Alexandr,thanks updated the answer. @melaos I have edited the answer to provide links
Pat
Cleaned up some of the markdown links, and changed `Moose::Intro` to `Moose::Cookbook`.
Brad Gilbert
The best intro to Moose I have seen is on Catalyzed.org: http://www.catalyzed.org/2009/06/a-gentle-introduction-to-moose.html Even as an experienced Perl programmer, I avoided Moose for a while because it seemed confusing.
Drew Stephens
+4  A: 

Currently I use Object::InsideOut whenever I want objects, its quite nice and will give you a lot of features over standard blessed hash objects. Having said that, if I was starting a new project I would seriously look at Moose.

While it is good to read the official PERL documentation, I would NOT recommend trying to role your own object framework, or building objects using hashes, its far to tempting to take the easy road and "peak" directly into the objects "private" variables completely breaking encapsulation, this will come back to bite you when you want to refactor the object.

Matthew Watson
+4  A: 

Perl objects are NOT just blessed hashes. They are blessed REFERENCES. They can be (and most often are) blessed hash references, but they could just as easily be blessed scalar or array references.

Michael Cramer
+6  A: 

Moose, definitely.

package Person;
use Moose;
has age => ( isa => Int, is => 'rw'); 
has name => ( isa => Str, is => 'rw'); 
1;

Immediately, you have for free a new() method, and accessor methods for the attributes you just defined with 'has'. So, you can say:

my $person = Person->new();
$person->age(34);
$person->name('Mike');
print $person->name, "\n";

and so on. Not only that, but your accessor methods come type-checked for free (and you can define your own types as well as the standard ones). Plus you get 'extends' for subclassing, 'with' for roles/traits, and all manner of other great stuff that allows you to get on with the real job of writing good robust maintainable OO code.

TMTOWTDI, but this one works.

Penfold
+1  A: 

On one foot, each class is a package; you establish (multiple, if desired) inheritance by setting the package variable @ISA (preferably at compile time); you create an object from an existing piece of data (often, but not always, an anonymous hash used to store instance variables) with bless(REFERENCE [, CLASSNAME]); you call object methods like $obj->methodname(@ARGS) and class methods like "CLASSNAME"->methodname(@ARGS). Multiple inheritance method resolution order can be altered using mro.

Because this is somewhat minimalistic and doesn't force encapsulation, there are many different modules that provide more or different functionality.

ysth
A: 

I highly recommend taking a look at Moose if you want to do OO in Perl. However, it's not very useful if you don't understand what OO in Perl means. To better understand how Perl OO works under the hood, I wrote an overview on my blog: http://augustinalareina.wordpress.com/2010/06/06/an-introduction-to-object-oriented-perl/

From a data structure point of view, an Object is reference with a few extra features. The interpreter knows to treat these special references as Objects because they have been "blessed" with the keyword "bless". Blessed references contain a flag indicating they are an Object. Essentially this means you can define and call methods on them.

For instance if you created a basic hashref, this wouldn't work: $hashref->foo();

But if you create a blessed hashref (aka an Object) this does work: $blessed_hashref->foo();

Moose is an excellent module for OOP in Perl because it creates an enforceable OO layer AND automagically handles accessor methods so you don't have to define a bunch of getters and setters. If you're interested in using Devel::Peak to see how the Perl interpreter stores objects, follow the link to the blog entry I posted above.

mmmpork