如果没有package..Perl,则无法调用方法“disconnect”

时间:2012-05-14 20:56:52

标签: perl module dbi

我写了一个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 ::在/var/www/domains/gabordx.tauri.hu/www/main.pl第7行调用的查询。 - > “& Query(”SELECT * FROM users“);”

有什么问题?

谢谢!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

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

否则你应该通过sql包引用它,就像这个

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

答案 2 :(得分:0)

一种方法是导出函数:

our @EXPORT = qw(DBImport DataFill Query);

perldoc Exporter