Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hello world OOP example in perl?

Tags:

perl

I'm reading a perl book but only has seen examples for functions by sub keyword.

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

How to rewrite the PHP below to perl?

class name {

   function meth() {
     echo 'Hello World';
   }
}

$inst = new name;
$inst->meth();
like image 826
compile-fan Avatar asked Nov 27 '22 01:11

compile-fan


2 Answers

The basic-perl way is:

In a 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 your script:

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

You may prefer to use Moose, though, in which case file 'Foo.pm' is:

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

Because Moose makes all the accessors 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;
like image 78
Alex Avatar answered Dec 12 '22 21:12

Alex


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

like image 33
friedo Avatar answered Dec 12 '22 20:12

friedo