in reply to Re: calling subroutines from variables
in thread calling subroutines from variables

This doesn't look like a dispatch table to me. If you're reading in a bunch of sub names from an external source, and calling them, order may matter. Hashes don't preserve that. "But I'm just suggesting using the table to convert from string to code ref! You can use the order of strings to control the order!" True, but why produce another hash when the symbol table (another hash) already exists, with ways to query it?

$ perl -le 'sub foo { }; print \&foo;print __PACKAGE__->can("foo")' CODE(0xf81930) CODE(0xf81930)
No non-strict code. And when I add new functions, no need to remember to update the symbol table - perl does that automatically.

Don't get me wrong. I like dispatch tables. I use them. A lot. This just doesn't seem like a use for them to me, mostly because it seems like the OP is trying to loop through them.

Replies are listed 'Best First'.
Re^3: calling subroutines from variables
by mr_mischief (Monsignor) on Aug 21, 2008 at 18:26 UTC
    I'm not sure I want an external source telling me which subs in my package to run without some control over which ones it's allowed to run. A hash of the allowed subrefs with a default error sub makes sense in that context.
    use strict; use warnings; sub one { print "one\n"; } sub two { print "two\n"; } sub tres { # some private sub they don't need to access } my %dispatch = ( 'one' => \&one, 'uno' => \&one, 'two' => \&two, 'dos' => \&two, 'default' => sub { print "sorry, $_[0] not found.\n"; }, ); my @do_these = qw( one two uno dos tres ); foreach my $do_this ( @do_these ) { if ( exists $dispatch{ $do_this } ) { $dispatch{ $do_this }->(); } else { $dispatch{ 'default' }->( $do_this ); } }