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

You are looking for Symbolic references. The following code does what you intend; However, I would think a dispatch table would be a cleaner, safer and less bug-prone solution to your issue. I, of course, have no idea what that issue is. Please read Why it's stupid to use a variable as a variable name before you use the code.

#!/usr/bin/perl use strict; use warnings; my $sub = 'do_this'; { no strict "refs"; print $sub->("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

And with a dispatch table, which leaves strict intact:

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

Replies are listed 'Best First'.
Re^2: Is it possible to use a scalar to call a subroutine?
by JavaFan (Canon) on May 06, 2010 at 17:32 UTC
    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");
      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
Re^2: Is it possible to use a scalar to call a subroutine?
by bradcathey (Prior) on May 06, 2010 at 18:32 UTC

    Okay, so this falls into the variable-for-a-variable camp. Which is why I stopped trying to this about 6 years ago and started using hashes. Which is basically what a dispatch table is doing.

    It seemed like a good idea at first, but now I'm seeing the logic.

    —Brad
    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot