in reply to 'Variable' sub names

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

Replies are listed 'Best First'.
Re^2: 'Variable' sub names
by ChrisR (Hermit) on Sep 15, 2005 at 13:20 UTC
    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

        Keep in mind that your example will call the coderef in $subs{$product} with the current contents of @_ just as if you'd called &namedsub;. If you want to pass an empty argument list you still need the parens: &{ $subs{ $product } }( ). See perldoc perlsub for more details.

        then one can see better that it is a sub call

        Perhaps one (since you count as one, I presume) can better see that, but I would think the general Perl-using population understands $foo->() to be a subref call. And even if I'm wrong about that, well, I just think it looks better. :-)

        Many thanks both work well.