2

我写了一个 perl 模块:

package sql;
use strict;
use XML::Simple;
use DBI;
use DBD::mysql;

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(DBImport DataFill);
our @EXPORT = qw(DBImport DataFill);

our $dbh;

sub DBConnect() {
    my $platform = "mysql";
    my $database = "databasename";
    my $host = "localhost";
    my $user = "user";
    my $pw = "password";
    my $dsn = "dbi:mysql:$database:localhost";
    $dbh = DBI->connect($dsn, $user, $pw);
    $dbh->do('SET NAMES utf8');
    return $dbh;
}

sub Query($) {
    my $sth = $dbh->prepare(shift);
    $sth->execute;
    while (my $ref = $sth->fetchrow_hashref()) {
        print $ref->{'email'};
    }
    $sth->finish();
}

BEGIN{
    $dbh = &DBConnect();
}

END{
    $dbh->disconnect();
}
1;

我尝试使用它:

#!/usr/bin/perl
use strict;
use CGI qw/:standard/;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use sql;

&Query("SELECT * FROM users");

但它不起作用。

错误消息:未定义的子例程 &main::Query 在 /var/www/domains/gabordx.tauri.hu/www/main.pl 第 7 行调用。 -> "&Query("SELECT * FROM users");"

有什么问题?

谢谢!

4

3 回答 3

2

您可以直接调用它,添加模块名称:

sql::Query("SELECT * FROM users");

或者您可以从模块中导入它

our @EXPORT_OK = qw(Query DBImport DataFill); # In the module

use sql qw(Query); # In caller code

或者您可以默认从 sql.pm 导出它

our @EXPORT = qw(Query DBImport DataFill);

@EXPORT和参考@EXPORT_OK: http: //perldoc.perl.org/Exporter.html#How-to-Export

于 2012-05-14T21:15:35.807 回答
1

您还需要导出Query,如下所示:

our @EXPORT_OK = qw(Query DBImport DataFill);
our @EXPORT = qw(Query DBImport DataFill);

否则你应该通过sql包来引用它,像这样

sql::Query("SELECT * FROM users");
于 2012-05-14T21:18:23.830 回答
0

一种方法是导出函数:

our @EXPORT = qw(DBImport DataFill Query);

perldoc 导出器

于 2012-05-14T21:14:06.843 回答