有什么方法perl
可以将变量从主脚本导入模块吗?
这是我的main.pl:
#!/usr/bin/perl -w
use DBI;
our $db = DBI->connect(...);
__END__
现在,我想在模块中使用$ db变量,因为我想避免重复的连接和重复的代码...可能吗?
您可以通过$main::db
在其他软件包中进行引用来实现。main
如果没有其他名称空间,则该名称空间始终指向主名称空间中的全局变量。您应该继续阅读package
。
请注意,这不是一个好主意,因为您的模块将依赖于main
连接。相反,您应该以允许您传递数据库句柄的方式构造对象。如果不惜一切代价要求进行数据库连接,则可以让它们抛出异常或创建自己的数据库句柄。
如果您不使用OO代码,则使数据库处理每个函数调用的参数。
还要注意,最好的做法是命名数据库handle $dbh
。
让我们看看非OO(Foo
)和OO(Bar
)的情况。
# this is package main (but you don't need to say so)
use strictures;
use DBI;
use Foo;
use Bar;
my $dbh = DBI->connect($dsn);
Foo::frobnicate($dbh, 1, 2)
my $bar = Bar->new(dbh => $dbh);
$bar->frobnicate(23);
package Foo;
use strictures;
sub frobnicate {
my ($dbh, $one, $two) = @_;
die q{No dbh given} unless $dbh; # could check ref($dbh)
$dbh->do( ... );
return;
}
package Bar;
use strictures;
sub new {
my ($class, %args) = @_;
die q{No dbh given} unless $args{dbh};
return bless \%args, $class;
}
sub frobnicate {
my ($self, $stuff) = @_;
$self->{dbh}->do(q{INSERT INTO bar SET baz=?}, undef, $stuff);
return;
}
__END__
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句