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

use strict; use warnings;

# always do those :)

$var1 = int(rand(6)) + 1 ; # i didn't want zero as an answer

my $var1 = ...

$var1 ='F'.$var1; # sub names can't start w/ numbers


Why not

my $var1 = 'F' . int(rand(6)) + 1;

??

$var1(); # this is where it crashes

see `perldoc perlref` for reference info

This is a soft ref and you're not doing it right....

try
 $var1->();
or
 {$var1}->();

Or better yet, do it with hard references:

#!/usr/bin/perl

use strict;
use warnings;

my %funcs = (
  1 => \&foo,
  2 => \&bar,
  3 => \&baz,
  4 => \&bot,
  5 => \&wam,
  6 => \&pow
);

$funcs{ int(rand(6)) + 1 }->();

sub foo { print "Foo\n"; }
sub bar { print "Bar\n"; }
sub baz { print "Baz\n"; }
sub bot { print "Bot\n"; }
sub wam { print "Wam\n"; }
sub pow { print "Pow\n"; }

HTH :)

Lee.M - JupiterHost.Net

--
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