S
Scott Bryce
I want to create a script that has random functionality.
I want the script to randomly choose between an unknown number of
subroutines and run one of them. By "unknown" I mean that the neither
names of the subroutines, the references to the subroutines, nor the
number of subroutines are hard coded into the script, but are determined
at runtime. This will allow me to add additional functions to the list
of possible random functions without having to update any other portion
of the script.
If that is as clear as mud, the code sample below demonstrates what I
want to do.
I came up with this. Is there a better way to do it?
use strict;
use warnings;
my @sub_list;
print &{$sub_list[int(rand(@sub_list))]};
BEGIN
{
push @sub_list, sub
{
return "Sub One was chosen\n";
};
push @sub_list, sub
{
return "Sub Two was chosen\n";
};
push @sub_list, sub
{
return "Sub Three was chosen\n";
};
}
I want the script to randomly choose between an unknown number of
subroutines and run one of them. By "unknown" I mean that the neither
names of the subroutines, the references to the subroutines, nor the
number of subroutines are hard coded into the script, but are determined
at runtime. This will allow me to add additional functions to the list
of possible random functions without having to update any other portion
of the script.
If that is as clear as mud, the code sample below demonstrates what I
want to do.
I came up with this. Is there a better way to do it?
use strict;
use warnings;
my @sub_list;
print &{$sub_list[int(rand(@sub_list))]};
BEGIN
{
push @sub_list, sub
{
return "Sub One was chosen\n";
};
push @sub_list, sub
{
return "Sub Two was chosen\n";
};
push @sub_list, sub
{
return "Sub Three was chosen\n";
};
}