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(); ... }