Sunday, February 8, 2009

Simple Perl modules

Making it already a rool to post technical details for which I have spent more than 20 minutes, I decided to post as well this.

keywords: How to write perl modules
PageRank: http://www.netalive.org/tinkering/serious-perl/

Answer: it's simple!

Create file StringManip.pm in Lib/ directory where you like with the following contents:

  1. package Lib::StringManip;  
  2.   
  3. use strict;  
  4.   
  5. use base 'Exporter';  
  6. our @EXPORT = ('trim');  
  7.   
  8. # Perl trim function to remove whitespace from the start and end of the string  
  9. sub trim  
  10. {  
  11.  my $string = shift;  
  12.  $string =~ s/^\s+//;  
  13.  $string =~ s/\s+$//;  
  14.  return $string;  
  15. }  
  16.   
  17. 1;  


Add the full path to Lib/StringManip.pm to PERL5LIB environment variable. In my case (win32) it is: PERL5LIB=%PERL5LIB%;D:\Programming\Perl

i.e. inside D:\Programming\Perl I have Lib/StringManip.pm. In Linux/Unix: export PERL5LIB=some_path/Lib/StringManip.pm.

Usage snippet:

  1. #!perl -w  
  2.   
  3. use strict;  
  4. use Lib::StringManip;  
  5.   
  6. print trim("  trim me!  ");  

No comments: