Because I always forget when I need to create a new class in
perl:
package Foo::Bar; use strict; use warnings; sub new { my $this = shift; my $class = ref($this) || $this; my $self = {}; bless $self, $class; $self->initialize(@_); return $self; } sub initialize { my $self = shift; } 1;
If you have any useful additions I’d love to know.
on said:
Install Moose.
http://search.cpan.org/dist/Moose/lib/Moose.pm
package Foo::Bar;
use Moose;
1;
and you get a Foo::Bar class with a constructor and no attributes. To install attributes you can do something like
has ‘foo’ => (is => ‘rw’, isa => ‘Str’);
on said:
If you can’t remember, isn’t this an indicator that Perl isn’t the language for you? 🙂
on said:
…or, indeed, for anyone?
on said:
my $class = ref($this) || $this;
This is an indication that you expect your constructor to be called as both a class method and an instance method. And that’s probably an indication of either a) a confused design or b) cargo-cult programming.
If you want a constructor that can be called as an instance method then create a separate subroutine for that (called “copy” or “clone” or something like that.
See the section that starts on slide 8 of http://www.slideshare.net/davorg/perl-teachin-part-2
on said:
package Foo::Bar;
use warnings;
use strict;
sub new{
my $class = shift;
# Initial instance data here
my $self = {
# …
};
bless $self, $class;
# Object initialisation here
# …
return $self;
}
# Example method
sub method{
my $self = shift;
my ($foo, $bar, $baf) = @_; #arguments
# …
}
1;
on said:
Haha. Christ. Perl doesn’t want anyone to use OOP in it for sure.