Snalk

Snalk » OS Tutorials » Unix » Creating and Using a Custom Perl Library

Reply
  #1 (permalink)  
Old 11-03-2008, 10:47 AM
Senior Member
 
Join Date: Aug 2008
Posts: 128
Post Creating and Using a Custom Perl Library

Creating and Using a Custom Perl Library



Creating a library is easy—just place the following into the file MyLib.pm:

package MyLib;

sub somefunction {
}

1;


That's about it. Just make sure the filename matches the package name. To use the library, you can place the following within a Mason document:

<%once>
use lib '/usr/local/www/lib';
use MyLib;
</%once>


The %once block contains Perl code that will be executed only the first time the object is requested (i.e., when the page is viewed or the component is called). Placing global code in these blocks can significantly enhance the performance of your web pages.

You can also include a library on a system-wide basis in your httpd.conf, as follows:

<Perl>
use lib '/usr/local/www/lib';
use MyLib;
</Perl>


Or, if the library can be found in the standard Perl library search path, you can just do this:

PerlModule MyLib

Once your custom library has been included, you can execute the functions within by using the syntax MyLib::somefunction(). You can add your own functions to this library as necessary.

# Should be named MyLib.pm and be placed in the module search path
package MyLib;

sub read_file ($) {
my ($file) = @_;
my %ret;
open(FILE, $file) or return undef;
while (my $line = <FILE>) {
chomp($line);
next if ($line =~ /^\s*$/); # skip blank lines
next if ($line =~ /^\s*#/); # skip comments

# Split into name and value
my ($name, $value) = split('=', $line, 2);
next unless ($name and $value);

# Remove single quotes
$value =~ s/^'//;
$value =~ s/'$//;

# Store value
$ret{$name} = $value;
}
close(FILE);
return \%ret;
}
sub read_pipe_file ($) {
my ($file) = @_;
my (@ret, $entry);
open(FILE, $file) or return undef;
while (my $line = <FILE>) {
chomp($line);
next if ($line =~ /^\s*$/); # skip blank lines
next if ($line =~ /^\s*#/); # skip comments

# Now retrieve name/values for current line
$entry = ();
while ($line =~ s/^\|([^=|]+)=([^|]*)//) {
$entry->{$1} = $2;
}
push @ret, $entry;
}
close(FILE);
return (@ret);
}

sub write_file ($$) {
my ($file, $data_ref) = @_;
open(FILE, ">$file") or return 0;
foreach my $name (keys %{$data_ref}) {
print FILE "$name='$data_ref->{$name}'\n";
}
close(FILE);
return 1;
}
1;
Reply With Quote
Reply

Bookmarks

Tags
creating perl library, perl in unix, perl library, unix, using perl library

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump



All times are GMT. The time now is 04:17 AM.
Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.