Boilerplate code for a perl class

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.

Filed under perl

6 comments

Comments are closed. These are preserved from the original site.

If you can't remember, isn't this an indicator that Perl isn't the language for you? :)

...or, indeed, for anyone?

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
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;

Haha. Christ. Perl doesn't want anyone to use OOP in it for sure.