Absolut Newbie wrote:
I have a program that generates a random number between 1 and 6. based on
the outcome I want to run a subroutine that corresponds to the result.
i.e if the result is 1 then the program should run sub F1. my question is
how can I dynamically call the subroutine.

i tried this but obviously it didn't work

$var1 = int(rand(6)) + 1 ; # i didn't want zero as an answer
$var1 ='F'.$var1; # sub names can't start w/ numbers

$var1(); # this is where it crashes

#assuming $var1 = F1 then it would run this
sub F1 {
print  "foo\n";
}

#assuming $var1 = F2 then it would run this.
sub F2 {
print  "bar\n";
}

Store references to the subroutines in an array something like this:

my @subs = ( \&F1, \&F2, \&F3, \&F4, \&F5, \&F6 );

And then call the one you want like this:

$subs[ rand @subs ]();



John
--
use Perl;
program
fulfillment

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to