#!/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 | [reply] [d/l] |
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;
}
| [reply] [d/l] [select] |
foreach my $product (@products) {
&{$subs{$product}};
}
then one can see better that it is a sub call.
Regards,
svenXY | [reply] [d/l] |
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.)
| [reply] |