Hi, world example of OOP in perl?

I am reading a perl book, but only saw examples for functions using the sub keyword.

Is there an example to define and use my own class?

How to rewrite PHP below in perl?

 class name { function meth() { echo 'Hello World'; } } $inst = new name; $inst->meth(); 
+4
source share
5 answers

The main perl way:

In the file "Foo.pm":

 use strict; use warnings; package Foo; sub new { my $class = shift; my $self = bless {}, $class; my %args = @_; $self->{_message} = $args{message}; # do something with arguments to new() return $self; } sub message { my $self = shift; return $self->{_message}; } sub hello { my $self = shift; print $self->message(), "\n"; } 1; 

In the script:

 use Foo; my $foo = Foo->new(message => "Hello world"); $foo->hello(); 

You can use Moose, but in this case the Foo.pm file:

 package Foo; use Moose; has message => (is => 'rw', isa => 'Str'); sub hello { my $self = shift; print $self->message, "\n"; } 1; 

Because Mus makes all the accessories for you. Your main file is exactly the same ...

Or you can use Moose extensions to make everything prettier, in which case Foo.pm becomes:

 package Foo; use Moose; use MooseX::Method::Signatures; has message => (is => 'rw', isa => 'Str'); method hello() { print $self->message, "\n"; } 1; 
+14
source

Modern Perl is a great book, available for free, which has a detailed section on writing OO Perl with Moose. (Begins on page 110 in the PDF version.)

+8
source

I would start with the perlboot man page .

From there you can go to perltoot , perltooc and perlbot ...

+7
source

I found this to be a more minimal version:

 package HelloWorld; sub new { my $class = shift; my $self = { }; bless $self, $class; return $self; } sub print { print "Hello World!\n"; } package main; $hw = HelloWorld->new(); $hw->print(); 

For those who want to play with this extra plug at https://gist.github.com/1033749

+5
source

An example posted by Sukima , but using MooseX :: Declare , which implements (without a source filter!) A more declarative syntax for Moose . This is about the same as the example provided by OP, as Perl is about to receive.

 #!/usr/bin/env perl use MooseX::Declare; class HelloWorld { method print () { print "Hello World!\n"; } } no MooseX::Declare; my $hw = HelloWorld->new; $hw->print; 

just a slightly more complex example shows more of the full power of the Moose / MooseX :: Declare syntax:

 #!/usr/bin/env perl use MooseX::Declare; class HelloWorld { has 'times' => (isa => 'Num', is => 'rw', default => 0); method print (Str $name?) { $name //= "World"; #/ highlight fix print "Hello $name!\n"; $self->times(1 + $self->times); } } no MooseX::Declare; my $hw = HelloWorld->new; $hw->print; $hw->print("Joel"); print "Called " . $hw->times . " times\n"; 
+3
source

All Articles