How do you write a wrapper module?

I am writing an additional loading module, I would like it to look like this:

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

My Download.pm should provide api sub download($url) . It will look for the LWP module, then the wget command, then the curl command, if they do not exist, it will use Socket .

How can I write a wrapper module?

+4
source share
1 answer

Here is an example of how I did it: How does it work? It checks some condition, and the creation of the object depends on this condition. And the routine also checks the reference type and calls the correct method

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 (some module):

 #!/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 (another module):

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

and the file /tmp/Adapt/Default.pm (default module):

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

and test script:

 #!/usr/bin/perl use strict; use warnings; require '/tmp/Adapt/Base.pm'; for (0..10) { my $test = Adapt::Base->new; $test->somesub; sleep 1; } 

output:

 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# 
+2
source

Source: https://habr.com/ru/post/1485372/


All Articles