4 ms·
Perl 5 does have an object system, one that was based in no small part on Python. About the biggest difference is the built-in constructor `bless` is simplisti
by b2gills 8y ago
Perl 5 does have an object system, one that was based in no small part on Python.
About the biggest difference is the built-in constructor `bless` is simplistic, and should be wrapped in a method.
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()
In Perl 5
#!/usr/bin/perl
use v5.12;
use warnings;
use feature 'signatures';
no warnings 'experimental';
# Allows for Python style constructor syntax
sub Person {
Person->new(@_);
}
package Person {
# this could be added to a base class instead
sub new($class, @args){
my $obj = bless {}, $class;
$obj->__init__(@args);
$obj;
}
sub __init__($self, $name){
$self->{name} = $name;
}
sub sayHi($self){
say 'Hello, my name is ', $self->{name}
}
}
my $p = Person('Swaroop');
$p->sayHi();
From a structural point of view, there is almost no difference. What little semantic difference there is could be put into a module.
Not that I would write it that way when Moose-like class modules exist
# Allows for Python style constructor syntax
sub Person($name){
# use the default constructor
Person->new( name => $name );
}
package Person {
use Moo;
no warnings 'experimental'; # subroutine signatures
has name => ( is => 'ro' );
sub sayHi($self){
say 'Hello, my name is ', $self->{name}
}
}
my $p = Person('Swaroop');
$p->sayHi
Moose was based on an early design for classes in Perl 6.
(and is apparently so good there are implementations of Moose in Python and Ruby)
class Person {
has $.name;
method sayHi(){
say 'Hello, my name is ', $.name
}
# Allows for Python style constructor syntax
submethod CALL-ME($name){
self.new( :$name )
}
}
my \p = Person('Swaroop');
p.sayHi();
Whenever you are rewriting code, you will see ways of making it simpler and more concise. So there are probably just as many instances where if you translated from Python to Perl 5 it would come out shorter. (Or even Python⇒Python, Perl5⇒Perl5)