in reply to Re: Is it possible to use a scalar to call a subroutine?
in thread Is it possible to use a scalar to call a subroutine?

I don't think I'd like a solution where named subs disappear as anon subs in hashes, using strings to look them up. Yeah, sure, strict is happy, but making strict happy isn't a goal. You've lost some of the benefits strict give you. Using a dispatch table just means you're doing what Perl is doing for you (using stashes) when using symbolic references - with the hash playing the role of a namespace.

I would use:

my $sub = \&do_this; print $sub->("Fred");

Replies are listed 'Best First'.
Re^3: Is it possible to use a scalar to call a subroutine?
by kennethk (Abbot) on May 06, 2010 at 17:39 UTC
    Fair criticism, though I would point out the total lack of context on the question at large. How about a compromise, which still lets the user specify their subroutine with a string, as per spec:

    #!/usr/bin/perl use strict; use warnings; my $sub_name = 'do_this'; my %dispatch_table = (do_this => \&do_this, do_that => \&do_that, ); print $dispatch_table{$sub_name}("Fred"); sub do_this { my $var = shift; return "My name is $var"; } sub do_that { my $var = shift; return "My name is not $var"; } __END__ My name is Fred