Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^2: Is it possible to use a scalar to call a subroutine?

by JavaFan (Canon)
on May 06, 2010 at 17:32 UTC ( [id://838768]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-24 11:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found