UID_Zero has asked for the wisdom of the Perl Monks concerning the following question:

I want to be able to specify an array of modules to use, and run the same subroutine in each one, like this:

--snip--
my @auth_methods = ('Wireless::Auth::Wisc', 'Wireless::Auth::CAE', 'Wi +reless::Auth::NIS'); foreach my $auth (@auth_methods) { my $rv = $auth::authorize($user, $pass); if($rv) { ... } }
--snip--

Is there a way to do this? I've seen things about using OO to do it, but I've never managed to get that working. The part I'm really worried about is letting the user specify the @auth_methods in a config file so it is easier to choose what authentication methods to use.

Replies are listed 'Best First'.
Re: User configured selection of modules
by eserte (Deacon) on Aug 30, 2004 at 18:17 UTC
    Yes, it's possible. One way is to use symbolic references:
    foreach my $auth (@auth_methods) { no strict 'refs'; my $rv = &{$auth . "::authorize"}($user, $pass); ... }
    In a OO world it would look like this:
    foreach my $auth (@auth_methods) { my $obj = $auth->new; my $rv = $obj->authorize($user, $pass); ... }
Re: User configured selection of modules
by Fletch (Bishop) on Aug 30, 2004 at 18:43 UTC

    Not as dynamic, but you might want to setup a hash of method => coderef and have the implementation modules register therein.

    package Wireless::Auth; our %methods; ... package Wireless::Auth::Wisc; sub Wisc { ... } $Wireless::Auth::methods{ 'Wisc' } => \&Wisc; 1;

    You could also wrap things up with a registerMethod routine rather than mucking with the hash directly. This way you can also use exists $methods{ $auth_type } to check what's been configured before calling $methods{ $auth_type }->( $user, $pass ) (warning for unknown methods and using a sub which always denies authorization).

Re: User configured selection of modules
by sgifford (Prior) on Aug 30, 2004 at 19:44 UTC
    In addition to the other suggestions here, keep in mind that you'll need to use those modules somewhere, with something like:
    use Wireless::Auth::Wisc;

    Doing that inside of an eval can stop your program from coming to a grinding halt if one of the modules isn't available.

Re: User configured selection of modules
by Aristotle (Chancellor) on Aug 30, 2004 at 21:20 UTC

    In addition to what's been said so far, you may want to take a look at Module::Pluggable.

    Makeshifts last the longest.