如果 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;启用:

Can't use string ("0") as an ARRAY ref while "strict refs" in use at ./return5.pl line 49.



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

use strict;禁用:
1468778  
04/01/2011  
30557 

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

请您参考如下方法:

问题是

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做。 (注意:同样的技术适用于 warnings 编译指示,您也应该使用它。)


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!