perl – 你如何编写包装模块?

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

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

我的Download.pm应该提供api子下载($url).它将寻找LWP模块,然后是wget命令,然后是curl命令,如果不存在这些,它将使用Socket.

我怎么写包装模块?

最佳答案 这是一些例子,我是怎么做到的:

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

文件/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# 
点赞