所以我的问题是基于这个问题: How to pass a subroutine as a parameter to another subroutine
问题是:我可以将参数/参数传递给子程序(它本身也是一个参数)吗?
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;
}
是否可以这样做?
$ 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);
}
实际用法:
my @tables = MySQLExe("SELECT table_name FROM information_schema.tables where table_schema='$table';",
$SelectResults);
答案 0 :(得分:5)
正如对相关问题的回答中所暗示的那样,您可能追求的是closure(另请参阅Perl.com article,Wikipedia entry):
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";
您需要注意,此处的演示代码包含了创建闭包时传递的信息,并且还使用了传递给闭包的参数。