5

use strict;如果被注释掉,我有几行代码可以工作。但是,我不想仅仅因为一小部分就禁用整个脚本。

我需要重新编码,或者以某种方式use strict;暂时禁用然后重新启用它。第一个选项更现实,但我不知道如何更改代码以在严格模式下工作。

my ($ctc_rec_ref) = get_expected_contacts($ctc,$fy);

my @expected_ctc_rec = @$ctc_rec_ref;

print $expected_ctc_rec[0][0]."\n";
print $expected_ctc_rec[0][1]."\n";
print $expected_ctc_rec[0][2]."\n";

sub get_expected_contacts
{
    my (@ctc_rec,$i) = ((),0);
    $STMT = "SELECT DISTINCT field1, field2, field3 FROM table WHERE field4 = ? AND field5 = ? AND field6 = 'E'";
    $sth = $db1->prepare($STMT); $sth->execute(@_); 
    while(@results = $sth->fetchrow_array())
    {
        push @{ $ctc_rec[$i] }, $results[0];
        push @{ $ctc_rec[$i] }, $results[1];
        push @{ $ctc_rec[$i] }, $results[2];

        $i++;
    }   
    return (\@ctc_rec);
}


启用use strict;

在 ./return5.pl 第 49 行使用“strict refs”时,不能使用字符串(“0”)作为 ARRAY 引用。

(第 49 行push @{ $ctc_rec[$i] }, $results[0];:)


禁用use strict;

1468778 
04/01/2011 
30557

如何重写此代码,使其像禁用严格模式一样工作?如果这是不可能的,可以use strict;暂时禁用,然后在脚本中为这段短代码重新启用?

4

2 回答 2

21

问题是

my (@ctc_rec,$i) = ((),0);

不做你认为它做的事。意思是一样的

my @ctc_rec = (0);
my $i;

strict正在做它应该做的事情并抓住你的错误。试着写:

my @ctc_rec;
my $i = 0;

反而。那应该摆脱错误。

在这种情况下,还有另一种方法可以消除错误,同时大大简化您的代码:使用selectall_arrayref

sub get_expected_contacts
{
   return $db1->selectall_arrayref(
     "SELECT DISTINCT field1, field2, field3 FROM table WHERE field4 = ? AND field5 = ? AND field6 = 'E'",
     undef, @_
   );
}

如果你真的故意做一些被禁止的事情strict(但知道你在做什么),你可以strict在本地禁用:

use strict;

# this code is strict
{ 
  no strict;
  # some code that is not strict here
}
# strict is back in effect now

但是,在您完全了解strict抱怨的内容以及为什么在这种情况下可以这样做之前,您永远不应该这样做。最好只禁用strict您必须禁用的部分。例如,您可以说no strict 'refs';允许符号引用而不禁用其他strict功能。(注意:同样的技术适用于警告编译指示,你也应该使用它。)

于 2011-04-11T15:01:00.267 回答
10

问题在于@ctc_rec 和$i 的声明。试试这个,你的代码应该停止给出严格的错误:

代替:

my (@ctc_rec,$i) = ((),0);

和:

my @ctc_rec;
my $i = 0;
于 2011-04-11T15:00:22.423 回答