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();
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;
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With