你怎么写包装模块?

时间:2013-06-10 07:10:47

标签: perl

我正在编写一个下载子模块,我希望它看起来像这样:

 Download.pm
 Download/Wget.pm
 Download/LWP.pm
 Download/Curl.pm
 Download/Socket.pm

我的Download.pm应提供api sub download($url)。它将查找LWP模块,然后查找wget命令,然后查找curl命令,如果不存在,则使用Socket

如何编写包装模块?

1 个答案:

答案 0 :(得分:2)

这是一些例子,我是怎么做到的: 这个怎么运作?它会检查某些条件,并根据这种情况创建对象。子程序还检查引用类型并调用正确的方法

file /tmp/Adapt/Base.pm(base module):

#!/usr/bin/perl

package Adapt::Base;

use strict;
use warnings;

sub new {
    my $class = shift;
    my $self;
    if ( time % 3 ) {
        require "/tmp/Adapt/First.pm";
        $self = \Adapt::First->new(@_);
    }
    elsif ( time % 2 ){
        require "/tmp/Adapt/Second.pm";
        $self = \Adapt::Second->new(@_);
    }
    else {
        require "/tmp/Adapt/Default.pm";
        $self = \Adapt::Default->new(@_); 
    }
    bless( $self, $class );
}

sub somesub {
    my $s = shift;
    my $self = $$s;
    if ( ref( $self ) eq 'Adapt::First' ) {
        $self->firstsub();
    }
    elsif ( ref( $self ) eq 'Adapt::Second' ) {
        $self->secondsub();
    }
    else {
        $self->defaultsub();
    }
}

1;

file /tmp/Adapt/First.pm(某个模块):

#!/usr/bin/perl

package Adapt::First;

use strict;
use warnings;

sub new {
    my $class = shift;
    my $self = {};
    bless( $self, $class );
}

sub firstsub {
    print "I am 1st sub.\n";
}

1;

file /tmp/Adapt/Second.pm(另一个模块):

#!/usr/bin/perl

package Adapt::Second;

use strict;
use warnings;

sub new {
    my $class = shift;
    my $self = {};
    bless( $self, $class );
}

sub secondsub {
    print "I am 2nd sub.\n";
}

1;

和文件/tmp/Adapt/Default.pm(默认模块):

#!/usr/bin/perl

package Adapt::Default;

use strict;
use warnings;

sub new {
    my $class = shift;
    my $self = {};
    bless( $self, $class );
}

sub defaultsub {
    print "I am default sub.\n";
}

1;

和测试脚本:

#!/usr/bin/perl

use strict;
use warnings;

require '/tmp/Adapt/Base.pm';

for (0..10) {
    my $test = Adapt::Base->new;
    $test->somesub;
    sleep 1;
}

输出:

dev# perl /tmp/adapt.pl
I am default sub.
I am 1st sub.
I am 1st sub.
I am 2nd sub.
I am 1st sub.
I am 1st sub.
I am default sub.
I am 1st sub.
I am 1st sub.
I am 2nd sub.
I am 1st sub.
dev#