Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: 'Variable' sub names

by ChrisR (Hermit)
on Sep 15, 2005 at 13:20 UTC ( [id://492203]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://492203]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-04-25 23:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found