所以我的问题是基于这个问题: 如何将子程序作为参数传递给另一个子程序
问题是:我可以将参数/参数传递给子程序(它本身也是一个参数)吗?
sub question {
print "question the term";
return 1;
}
my $question_subref = \&question;
answer($question_subref);
sub answer {
my $question_subref = shift;
print "subroutine question is used as parameters";
# call it using arrow operator if needed
$question_subref -> ($PassSomethingHere,$SomethingElse);
return 1;
}
Run Code Online (Sandbox Code Playgroud)
是否有可能做到这一点?
$ question_subref - >($ PassSomethingHere,$ SomethingElse);
下面是实际的代码:
my $SelectResults = sub {
my @results;
$sql = $_[0];
$sth = $_[1];
$sql =~ s/select/SELECT/gi;
if(StrContains($sql, "SELECT"))
{
@results= $sth->fetchrow_array();
foreach my $tab (@results) {
print $tab . "\n";
}
}
return @results;
};
sub MySQLExe
{
my @results;
my $db = "fake";
my $usr = "user";
my $pw = "password";
$db_handle = DBI->connect("dbi:mysql:database=$db;mysql_socket=/var/lib/mysql/mysql.sock;", $usr, $pw) \
or die "Connection Error: $DBI::errstr \n";
my $sql = $_[0];
print $sql . "\n";
#Prepare SQL query
my $sth = $db_handle->prepare($sql)
or die "Couldn't prepare query '$sql': $DBI::errstr\n";
$sth->execute
or die "Couldn't execute query '$sql': $DBI::errstr\n";
# I can't seem to get this to work...
# optional Function here - get rows from select statement or something else.
# pass in the function holder as the second parameter
my $Func = $_[1];
@results = $Func -> ($sql, $sth);
#disconnect from database
$sth->finish;
$db_handle->disconnect or warn "Disconnection error: $DBI::errstr \n";
return(@results);
}
Run Code Online (Sandbox Code Playgroud)
和实际用法:
my @tables = MySQLExe("SELECT table_name FROM information_schema.tables where table_schema='$table';",
$SelectResults);
Run Code Online (Sandbox Code Playgroud)
正如在链接问题的答案中暗示的那样,你可能追求的是一个闭包(另见Perl.com文章,维基百科条目):
sub make_questioner {
my ($text) = @_;
return sub {
my ($politeness) = @_;
print $text, $politeness, "\n";
my $answer = <>;
chomp $answer;
$answer;
};
}
my $questioner = make_questioner("What... is your name");
my $name = $questioner->(', please');
print "Your name is '$name'.\n";
Run Code Online (Sandbox Code Playgroud)
你会注意到这里的演示代码包含了创建闭包时传递的信息,并且还使用了传递给闭包的参数.