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 being what the process()-sub does.
#!/usr/bin/perl -w
use strict;
sub process {
...
}
My issue: the input for the main script is a (possibly long) list of things, while processing that list i get continuous “Subroutine redefined” errors (obviously). Is there any way to “un-use” a module?
Due to the fact that the library of possible “actions” to include may grow in the future, i thought this way of including modules dynamically would be the best approach. Many thanks for your help 🙂
As @pilcrow said, you can solve this issue quickly by using
requireinstead ofuse, but, I think this is a good example where Polymorphism is to be used.You can create a base class like:
And then, create your processors as packages that inherit from this base package.
Then your code could look like:
Of course, the modifications assume that
$_is in the form ofProcessors::Foofor example. Even if you can not modify the content of your@data, I think you can generate the name of the processor so that you are able to invoke itsprocess()method.If you want to be a show-off, you could create a
Factoryobject that will return instances of your processors based on the value of$_:Then, your code would look like: