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

I have an application that is used to collect and process data for a number of different
products. Part of the process is a sub that will have to be written for each product.

I could do this by something like:

if(product_type eq ‘a’) {
call a();
} elsif(product type eq ‘b’);{
call b()
} elsif etc etc

Is there a way of say passing an argument to the main processing subroutine, where
these calls are made, that gives the name of the subroutine to be called? In this
way I would not have to modify the main processing sub every time a new
product had to be implemented.

Replies are listed 'Best First'.
Re: 'Variable' sub names
by svenXY (Deacon) on Sep 15, 2005 at 13:09 UTC
    Hi,
    use a dispatcher:
    #!/usr/bin/perl use strict; use warnings; my %subs = ( prod1 => \&sub_prod1, prod2 => \&sub_prod2 ); foreach my $product (@products) { &{$subs{$product}}("lala"); } sub sub_prod1 { print "1 ", shift, "\n"; } sub sub_prod2 { print "2 ", shift, "\n"; }

    Update: the cast to a sub: &{...}, thanks to ++ChrisR
    Update: adding () after the sub cast: &{...}(), thanks to ++Fletch
    Regards,
    svenXY
      You missed something. Your script produces Useless use of hash element in void context. You need to use $subs{$product}->().
      #!c:\perl\bin\perl.exe -w use strict; use warnings; my @products = qw (prod1 prod2); my %subs = ( prod1 => \&sub_prod1, prod2 => \&sub_prod2 ); foreach my $product (@products) { $subs{$product}->(); } sub sub_prod1 { print 1; } sub sub_prod2 { print 2; }
        Hi,
        or so:
        foreach my $product (@products) { &{$subs{$product}}; }
        then one can see better that it is a sub call.
        Regards,
        svenXY
Re: 'Variable' sub names
by chromatic (Archbishop) on Sep 15, 2005 at 17:41 UTC

    If products were objects, you could define a class for each type of product and call a single method on each object. With the individual classes, you could override the method to do the appropriate thing for the product type.

    (This is the Replace Conditional with Polymorphism refactoring. It's one of my favorites.)