4

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

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

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

如何编写包装模块?

4

1 回答 1

2

这是一些示例,我是如何做到的:它是如何工作的?它检查某些条件,并根据该条件创建对象。子程序还检查引用类型并调用正确的方法

文件 /tmp/Adapt/Base.pm(基本模块):

#!/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;

文件 /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;

文件 /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# 
于 2013-06-10T08:48:56.327 回答