Hello world OOP example in perl?
I'm reading a perl book but only has seen examples for functions b开发者_StackOverflowy 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.)
I would start with the perlboot man page.
From there you can move on to perltoot, perltooc, and perlbot...
I found this is a more minimalistic 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 anyone who wishes to play with this further fork it at https://gist.github.com/1033749
The example as posted by Sukima but using MooseX::Declare which implements (without a source filter!) a more declarative syntax for Moose. It is about as close to the example given by the OP as Perl is going to get.
#!/usr/bin/env perl
use MooseX::Declare;
class HelloWorld {
method print () {
print "Hello World!\n";
}
}
no MooseX::Declare;
my $hw = HelloWorld->new;
$hw->print;
an only slightly more complicated 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";
精彩评论