Wednesday, February 3, 2010

Perl tips - creating your own utility library using classes

- Creating your own library of utility functions
  • Create a file MyUtils.pm
  • For each new class in it, start with package MyUtils::MyClass.
  • Create static class attributes using our $attr.
  • Create methods using sub meth1{ my @args = @_; ... }. If this will be used as an object method (not static), remember to treat first entry of @_ as reference to object.
  • Object is nothing but a normal data type (like hash or list) and is allocated in the new method (that you must define) and returned.
  • The new method should be like sub new {my ($class, $otherargs) = @_; my ;...; my $ref_to_somedata; bless , $class; return $ref_to_somedata;}.
  • Start with package MyUtils::MyClass::MySubClass to create a subclass.
Accessing your library MyUtils.pm
  • First include use lib "path/to/dir/containing/MyUtils.pm"; use MyUtils; in the beginning of the .pl file.
  • Use MyUtils::MyClass::meth1 to access static methods.
  • Use $MyUtils::MyClass::attr to access static attribute $attr of the class (note the $).
  • Use MyUtils::MyClass->new(...) to create an object.
  • Use MyUtils::MyClass::MySubClass wherever you are using MyUtils::MyClass for subclasses.
Other useful stuff
  • Use $ENV{env_variable} to access the value of environment variable $env_variable in Perl code, (useful for specifying "path/to/dir/" of .pm file).

No comments:

Post a Comment