虽然用perl用了一段时间,但是从来没有独立写过一个module。因为要开始用perl写些selenium的
测试软件了,所以需要用到这个。
我现在需要的其实很简单,我需要将大部分的常用的功能部件(functions)放到一起,然后随时调用。我目前还不需要复杂的OO功能。因为以前没有搞过,所以今天很花了一些时间。
perl的module文件可以非常简单,我的如下:
====== perl module file ======
#!/usr/bin/perl#
#file name: Util.pm
package Util;
use Carp;
use IO::Socket;
require Exporter;
$VERSION='0.01';
@ISA=qw(Exporter);
@EXPORT = qw(pinghost printhash);
sub printhash {
my $hash=shift;
my %h=%$hash;
foreach (sort keys %h){
print "\nkey=[$_] value=[$h{$_}]";
}
}
sub pinghost{
# input: ($host, $port)
# output: return 1 if remote host active on given port, otherwise, return 0
my ($host, $port)= @_;
my $return = 0;
# Try to connect
my $remote = IO::Socket::INET->new(
Proto => "tcp",
PeerAddr => $host,
PeerPort => $port,
Timeout => 8,
);
# verify response
if ($remote) {
print "$host is alive\n";
close $remote;
$return = 1;
}
return $return;
}
1;# don't forget this line
========= End of the file ======
如果需要调用的话,可以如下:
====== use the perl module =====
#!/usr/bin/perl
use lib '/home/yi/workspace/ipawebgui/testuitl';use Util ;$host="
server";
$port=5000;
if (pinghost($host,$port)) {
print "\nserver [$host:$port] alive";
}
else {
print "\nserver [$host:$port] no response";
}
printhash(\%ENV);
============== End of file ==========
这里比较关键的是两个:
1。 在module文件里面需要有Exporter,其目的是将module里面的子程序告知调用的主程序
2。在调用module的主程序里面,需要指明被调用的module的文件地址(use lib 语句)和调用的module的名字(Util)
这个人写的很不错,比较完备:
http://springfield.pm.org/meetings/modules.html