模块的perl变量

perl variable to module

我正在尝试执行存储在模块中的查询,但该查询包含一些从主文件中读取的变量并且无法正常工作。

主文件中的变量在模块内不可访问(其空白)。

代码如下:

sql.pm

package sql;

use parent 'Exporter'; 

our @EXPORT = qw(%query);

our %query = (
    one => "SELECT isnull(BusinessEntityID, '') as BusinessEntityID,
       isnull(Title, '') as Title,
       isnull(FirstName, '') as FirstName,
       isnull(LastName, '') as LastName,
       isnull(Suffix, '') as Suffix,
       isnull(JobTitle, '') as JobTitle

FROM HumanResources.vEmployee
where BusinessEntityID = ".$id."
order by BusinessEntityID"

);

1;

main.pl

use strict;
use warnings;

use sql;

my $id = 273;
my $query_main = "$query{one}";

print $query_main;

这将使用 where BusinessEntityID = 而不是 where BusinessEntityID = 273 打印查询

谢谢!

在你的sql包的范围内没有词法$id变量,所以它被评估为undef,它被字符串化为空字符串

当您尝试 运行 您的程序时,您会看到警告消息。请不要忽视它们,尤其是当您寻求帮助时:它们非常重要

请合理命名您的模块。像 sql 这样的名称表示 pragma,并影响以下所有代码。一个模块将使用 Capital::Letters 并且应该与 CPAN

中的任何东西有很大不同

我认为您应该将您的库限制为仅包含常量的子例程,并且您应该避免将值插入 SQL 查询字符串

例如

package My::Sql;

use Exporter 'import';

our @EXPORT = qw/
    QUERY_ONE
/;

use constant {
    QUERY_ONE => "SELECT isnull(BusinessEntityID, '') as BusinessEntityID,
       isnull(Title, '') as Title,
       isnull(FirstName, '') as FirstName,
       isnull(LastName, '') as LastName,
       isnull(Suffix, '') as Suffix,
       isnull(JobTitle, '') as JobTitle

FROM HumanResources.vEmployee
where BusinessEntityID = ?
order by BusinessEntityID"

);

1;

如果你那么

use My::Sql;

my $sth = $dbh->prepare(QUERY_ONE);
$sth->execute(42);

那你的代码至少应该能运行,但设计上还是很欠缺

当然,在 Perl 中可以从另一个包访问一个包的全局变量。
但这意味着您必须将所有 localmy 变量转换为全局变量。
会很乱。
我强烈反对这样做。

简化占位符变量管理的方法之一是使用Template Toolkit,如下所示:

#!/usr/bin/perl
use strict;
use warnings;
use Template;

my $template = <<'CUT';
SELECT isnull(BusinessEntityID, '') as BusinessEntityID,
       isnull(Title, '') as Title,
       isnull(FirstName, '') as FirstName,
       isnull(LastName, '') as LastName,
       isnull(Suffix, '') as Suffix,
       isnull(JobTitle, '') as JobTitle

FROM HumanResources.vEmployee
where BusinessEntityID = [% id %]
order by BusinessEntityID
CUT
;

my $id=100;
my ($param1,$paramN);
my $vars = {
    'id'=>$id,
    'param1'=>$param1,
     #...
    'paramN'=>$paramN,
};

my $tp = Template->new();
my $out;
$tp->process($template, $vars, $out)
    || die $template->error();
print($out);

输出

SELECT isnull(BusinessEntityID, '') as BusinessEntityID,
       isnull(Title, '') as Title,
       isnull(FirstName, '') as FirstName,
       isnull(LastName, '') as LastName,
       isnull(Suffix, '') as Suffix,
       isnull(JobTitle, '') as JobTitle

FROM HumanResources.vEmployee
where BusinessEntityID = 100
order by BusinessEntityID

但是如果您要运行使用不同的参数多次执行相同的查询,您应该使用 Borodin 的回答中所示的参数绑定,以避免性能损失。