【问题标题】:How can I avoid this error produced while using 'strict'?如何避免使用“严格”时产生的这个错误?
【发布时间】:2011-08-03 03:36:25
【问题描述】:

如果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;

不能使用字符串 ("0") 作为 ARRAY ref 而“严格参考”在使用 ./return5.pl 第 49 行。

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


禁用use strict;

1468778 
04/01/2011 
30557

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

【问题讨论】:

    标签: arrays perl multidimensional-array strict


    【解决方案1】:

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

    替换:

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

    与:

    my @ctc_rec;
    my $i = 0;
    

    【讨论】:

    • 谢谢 - 尽管您确实首先回答了可行的解决方案,但 cjm 给了我更多的考虑和工作。
    【解决方案2】:

    问题是

    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 pragma,您也应该使用它。)

    【讨论】:

    • 非常感谢。这真的帮了我很多,而不仅仅是提供一种解决方案
    • selectall_arrayref 方法效果很好。我从来不知道DBI 的那个功能/方法,看起来它将来会很方便
    • 传递undef 和离开\%attr 有什么区别?
    • @CheeseConQueso,如果您将\%attr 排除在外,那么@_ 中的第一个参数将被视为\%attr。您可以传递一个空的 hashref 而不是 undef,但如果您想绑定占位符,您必须\%attr 传递一些东西。
    • 明白了......这是有道理的。他们应该重新措辞或提及您在search.cpan.org/~timb/DBI-1.616/… 中所说的话 - 它说In general, you can ignore \%attr parameters or pass it as undef.
    猜你喜欢
    • 1970-01-01
    • 2010-11-17
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多