perl变量到模块

问题描述 投票:0回答:2

我正在尝试执行存储在模块中的查询,但查询中有一些从主文件中读取但不起作用的变量。

模块内部无法访问主文件中的变量(空白)。

这是代码:

SQL.屏幕

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;

卖弄.评论

use strict;
use warnings;

use sql;

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

print $query_main;

这将打印查询,其中BusinessEntityID =,而不是BusinessEntityID = 273

谢谢!

perl perl-module
2个回答
3
投票

在你的$id包的范围内没有词法sql变量,所以它被评估为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);

那么你的代码至少应该起作用,但设计仍然非常缺乏


1
投票

当然,在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的答案所示,以避免性能损失。

© www.soinside.com 2019 - 2024. All rights reserved.