Perl: "unincluding" modules

So, I have a program like this:

#!/usr/bin/perl -w use strict; foreach (@data) { if($_ eq "foo") { use Foo; process(); } if($_ eq "bar") { use Bar; process(); } ... } 

Each included module is somewhat similar, the only difference is what process () does - sub.

 #!/usr/bin/perl -w use strict; sub process { ... } 

My problem: the entry for the main script is a (possibly long) list of things, and when processing this list I get continuous "overridden" errors (obviously). Is there a way to not use the module?
Due to the fact that the library of possible "actions" for inclusion may grow in the future, I thought that this way of including modules dynamically would be a better approach. Many thanks for your help:)

+4
source share
1 answer

As @pilcrow said, you can quickly solve this problem by using require instead of use , but I think this is a good example where Polymorphism is .

You can create a base class, for example:

 package Processors::Base; sub new{ my $class = shift; return bless {}, $class; } sub process{ die "You can only use a subclass of me"; } 1; 

And then create your processors as packages that inherit from this base package.

 package Processors::Foo; sub process{ ... do stuff ... } 1; 

Then your code might look like this:

 #!/usr/bin/perl -w use strict; for my $pkg (@data) { (my $path = $pkg) =~ s{::}{/}g; require "$path.pm"; $pkg->process; ... } 

Of course, modifications assume that $_ has the form Processors::Foo , for example. Even if you cannot change the contents of your @data , I think you can generate a processor name so that you can call its process() method.

If you want to become a champion, you can create a Factory object that will return instances of your processors based on the value of $_ :

 package Processors::Factory; sub get_instance{ my ($self, $processor_name) = @_; my $full_processor_name = sprintf('Processors::%s', ucfirst($processor_name) ); (my $full_processor_path = $full_processor_pkg) =~ s{::}{/}g; require "$full_processor_path.pm"; my $processor = $full_processor_name->new(); return $processor; } 1; 

Then your code will look like this:

 #!/usr/bin/perl -w use strict; use Processors::Factory; foreach (@data) { Processors::Factory->get_instance( $_ )->process(); ... } 
+7
source

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


All Articles