in reply to Re: 'Variable' sub names
in thread 'Variable' sub names

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; }

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