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.

6 thoughts on “Boilerplate code for a perl class

  1. 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

  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;

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.