Thursday, May 14, 2009

Quickly Create an Object Oriented Perl Module

  1. Create a directory under the current directory for your module
  2. Create a file called yourmodule.pm
  3. Put the following line at the top:
    package yourmodule;
  4. Now paste the following and edit the require code to include all the libraries your package needs
    use 5.0;
    #use strict;
    use warnings;

    require Win32::GuiTest, HTTP::Request, XML::Smart, Exporter;
    our @ISA = qw(Exporter);
    our %EXPORT_TAGS = ( 'all' => [ qw() ] );
    our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
    our @EXPORT = qw( );

    our $VERSION = '1.00';

  5. Create a constructor subroutine; it needs to bless a reference to the object as its last line (put whatever you like before that)
    sub new {
    my $self = { FOO => 1, BAR => 0};
    bless $self, "yourmodule";
    }
  6. Load the module in your Perl file

    use lib './yourmodule'; # this adds the module directory to your include path
    use yourmodule; # this loads your module
  7. You can now call your module from your perl file:
    my $barf = yourmodule->new();
    print $barf->get_stuff() . "\n";
    exit(0);

  8. Remember! when you call your package's methods using an object ($object->method()), the first argument is a reference to the object-- you can restore 'normal' operation (if you just pasted the sub routine from within a normal perl file) by just adding my $self=shift; to the top of your sub routine.

No comments:

Labels

Blog Archive

Contributors