Thu, 17 Apr 2008

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.

[] | # Read Comments (6) |

Comments

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');
Posted by Florian Ragwitz at Thu Apr 17 11:52:31 2008
If you can't remember, isn't this an indicator that Perl isn't the language for you? :)
Posted by Rob Kendrick at Thu Apr 17 12:50:19 2008
...or, indeed, for anyone?
Posted by Nick Moffitt at Thu Apr 17 13:16:52 2008
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
Posted by Dave Cross at Thu Apr 17 16:31:24 2008
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;
Posted by Dan at Wed Oct 1 20:44:05 2008
Haha. Christ. Perl doesn't want anyone to use OOP in it for sure.
Posted by o at Thu Dec 31 03:51:57 2009

Name:


E-mail:


URL:


Comment:


Please enter "fudge" to prove you are a human