m1m1k
m1m1k

Reputation: 1435

In Perl, pass a parameter into a subroutine which is also a parameter

So my question is based off of this SO question: How to pass a subroutine as a parameter to another subroutine

Question is: can I pass arguments/parameters into the subroutine (which is also itself a parameter)?

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

Is it possible to do this?

$question_subref -> ($PassSomethingHere,$SomethingElse);


Heres the actual code:

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);
}

And Actual usage:

my @tables = MySQLExe("SELECT table_name FROM information_schema.tables where table_schema='$table';", 
    $SelectResults);

Upvotes: 1

Views: 404

Answers (1)

Ed.
Ed.

Reputation: 2062

As hinted in an answer to the linked question, what you're probably after is a closure (see also 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";

You'll note that the demo code here incorporates information passed on creating the closure, and also uses a parameter passed to the closure.

Upvotes: 5

Related Questions