sicrj has asked for the wisdom of the Perl Monks concerning the following question:

Hello,


I want to expand a variable name into a call to a subroutine. Seems doable, but I'm at a loss as of yet.


Info:

perl v5.6.0
Mandrake Linux 7.2 - 2.2.17

What I want:
Based on an argument given, I need to cycle through some number of subroutines. Example code follows, hopefully it's clear enough to explain my point:

$count = shift; for($runs = 1; $runs <= $count; $runs++){ &func_"$runs"; } sub func_1{} sub func_2{} sub func_3{} # etc, etc, etc.
So, if a user enters ./program.pl 8, I want to go through subroutines 1 through 8. I've also tried calling the subroutines by using:
func_"$runs"();
No luck there either. And, I've tried various combinations of quote marks.
Any ideas are much appreciated, and I apologize if this is a rtfm'er.

Replies are listed 'Best First'.
Re (tilly) 1: Expanding Variable Names in Calls to Subroutines
by tilly (Archbishop) on Jul 11, 2001 at 06:34 UTC
    @runs = ( sub { print "This is one subroutine\n"; }, sub { print "This is another subroutine\n"; }, # etc ); $_->() foreach @runs;
    You can also generate references to named subroutines with \&foo.

    Another way to do it is to use symbolic references, but that is Not Recommended. See strict for details and strict.pm for details of why to use strict to guarantee that you do not accidentally make that mistake.

Re: Expanding Variable Names in Calls to Subroutines
by tachyon (Chancellor) on Jul 11, 2001 at 06:38 UTC

    What you want to do is called using a symbolic reference. For details see perlman:perlref

    It is generally considered a rather bad idea to use symbolic references without a good reason.

    The strict pragma was developed to stop you doing this amongst many other generally bad things. You will thus need to use no strict refs or worse still no strict! For details on why strict is a good idea see Use strict warnings and diagnostics

    There are almost always better ways to do it.

    You will make your code hard to understand and maintain if you use a variable as the name of the subroutine that you want to call.

    OK warning lecture aside here is how you do it :-)

    use strict; no strict 'refs'; sub a1 { print "a1\n" } sub a2 { print "a2\n" } sub a3 { print "a3\n" } sub a4 { print "a4\n" } foreach my $num (1..4) { my $sub_to_call = "a".$num; &$sub_to_call; }

    I'm not sure this will really help you!

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: Expanding Variable Names in Calls to Subroutines
by LD2 (Curate) on Jul 11, 2001 at 06:37 UTC
      Many thanks. This works perfectly.