perl 模块化编程实例

1. 在当前目录创建 文件 Bruce目录,下面有Util.pm文件,内容如下:

package Bruce::Util;
use strict;
use Exporter;
use File::Path;

our @ISA =qw(Exporter);
our @EXPORT = qw(GetTimeStampStr CreateDirIfNeed LogMsg);
our @EXPORT_OK = qw($LogFilePath);
our @version = 1.0;


our $LogFilePath;


sub GetTimeStampStr()
{
	my $timestr = localtime(time());
	return $timestr;
}

sub CreateDirIfNeed
{
	my $Dir = shift;
	if (-e $Dir and -d $Dir)
	{
		return 0;
	}
	print("makepath $Dir"); 	
	eval {mkpath($Dir)};
	if($@) 
	{ 
		print("Make   path   [$Dir]   failed:$@"); 
		return -1;
	} 
	return 0;
}

sub LogMsg()
{	
	my $Param1 = shift;
	my $Str = &GetTimeStampStr()." -- ".$Param1;
	`echo $Str>>$LogFilePath`;
}

1;
__END__

2. 在当前目录创建测试文件test.pl,内容如下:

#!perl -w
use strict;
use File::Basename;
BEGIN{
	push(@INC, dirname(__FILE__));
}
use Bruce::Util;  #必须放到BEGIN后面
print __FILE__;
print "\nThe Dir is:";
my $path= dirname(__FILE__);
print $path;
print "\n@INC\n";

print GetTimeStampStr();

CreateDirIfNeed("go\\go\\go.txt");

$Bruce::Util::LogFilePath = "$path\\log.txt";

&LogMsg("asfasfadfa");


运行如下:




你可能感兴趣的:(perl 模块化编程实例)