Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: call sub in string

by Kanji (Parson)
on Feb 16, 2002 at 09:01 UTC ( [id://145828]=note: print w/replies, xml ) Need Help??


in reply to call sub in string

You're probably after an symbolic reference, and were almost but not quite there with your snippet...

sub function_1 { print "One\n" } sub function_2 { print "Two\n" } { # Allow symbol table manipulation. # You do use strict;, right? :) no strict 'refs'; foreach my $no ( 1 .. 2 ) { &{ "function_$no" }; # <--- THIS THING } }

... but that could potentially blow up in your face if $no turned out to be something unexpected unless you wrapped the whole shebang inside an eval or made good use of can.

The more preferable (and use strict;-happy) way of doing this sort of thing is using something called a dispatch table, which'd look something like ...

sub function_1 { print "One\n" } sub function_2 { print "Two\n" } my %functions = ( 'DEFAULT' => sub { print "Huh?\n" }, 1 => \&function_1, 2 => \&function_2, ); foreach my $no ( 1 .. 3 ) { $no = 'DEFAULT' unless exists $functions{$no}; $functions{$no}->(); }

    --k.


Replies are listed 'Best First'.
Re: Re: call sub in string
by demerphq (Chancellor) on Feb 18, 2002 at 11:22 UTC
    While in principle you are correct that dispatch tables are a good idea for this kind of thing, I would say that for this case or at least given how this case was posed dispatch tables would be overkill.

    The easier way to accomplish his goal without using symbolic refs and without using a disptach table is to simply loop over a list of subrefs.

    foreach my $sub (\&function_1,\&function_2) { $sub->(); }
    Of course Im somewhat curious why any good programmer would handroll numbered functions (i can see it with autogenerated subs, kinda), but I suspect our OP is a bit new to 'tings.

    :-)

    Yves / DeMerphq
    --
    When to use Prototypes?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-03-29 01:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found