正如标题所说,perl在查询不存在的元素之后将虚拟元素添加到数组中.查询后数组大小增加.举例说明:
my $rarr;
$rarr->[0][0] = 'S';
$rarr->[0][1] = 'MD';
$rarr->[1][0] = 'S';
$rarr->[1][1] = 'PRP';
my $crulesref;
$crulesref->[0] = $rarr;
check_rule('aa', 0);
if($rarr->[3][0] == 'M'){ # just check a not existing element
print "m\n";
}
check_rule('bb', 0);
if($rarr->[5][0] == 'M'){ # again: just check a not existing element
print "m\n";
}
check_rule('cc', 0);
sub check_rule($$)
{
my ($strg,$ix) = @_;
my $aref = $crulesref->[$ix];
my $rule_size = @$aref;
{print "-----$strg aref:$aref rs:$rule_size aref:'@$aref'\n";
for(my $t1 = 0; $t1 <$rule_size; $t1++){
print "t1:$t1 0:$aref->[$t1][0] 1:$aref->[$t1][1]\n";
}
}
}
Run Code Online (Sandbox Code Playgroud)
运行的结果是:
en@en-desktop ~/dtest/perl/forditas/utf8_v1/forditas/test1 $ perl v15.pl
-----aa aref:ARRAY(0x90ed8c8) rs:2 aref:'ARRAY(0x9106cac) ARRAY(0x9106d24)'
t1:0 0:S 1:MD
t1:1 0:S 1:PRP
m <-------------- finds the non existing
-----bb aref:ARRAY(0x90ed8c8) rs:4 aref:'ARRAY(0x9106cac) ARRAY(0x9106d24) ARRAY(0x9107508)'
t1:0 0:S 1:MD
t1:1 0:S 1:PRP
t1:2 0: 1: <-- undesired dummy due to inquiry
t1:3 0: 1: <-- undesired dummy due to inquiry
m <-------------- finds the non existing
-----cc aref:ARRAY(0x90ed8c8) rs:6 aref:'ARRAY(0x9106cac) ARRAY(0x9106d24) ARRAY(0x9107904) ARRAY(0x9107508) ARRAY(0x910e860)'
t1:0 0:S 1:MD
t1:1 0:S 1:PRP
t1:2 0: 1: <-- undesired dummy due to inquiry
t1:3 0: 1: <-- undesired dummy due to inquiry
t1:4 0: 1: <-- undesired dummy due to inquiry
t1:5 0: 1: <-- undesired dummy due to inquiry
Run Code Online (Sandbox Code Playgroud)
如果查询元素存在,是否没有其他方法可以避免这种情况而不是在每次调查之前询问?我试图提高速度,这些查询减慢了代码的速度,使其不易阅读.
提前感谢有用的提示.
TLP*_*TLP 12
这是你看到的自动化.如果您$ref->[3][0]只需检查即可访问内存:
if ($ref->[3][0] eq 'M' )
Run Code Online (Sandbox Code Playgroud)
然后首先$ref->[3]必须存在,才能检查其元素号为零,因此它是通过自动生成创建的.您需要首先检查是否$ref->[3]存在或已定义以避免创建它.
if (defined($ref->[3]) && $ref->[3][0] eq 'M')
Run Code Online (Sandbox Code Playgroud)
此外,你应该总是使用:
use strict;
use warnings;
Run Code Online (Sandbox Code Playgroud)
然后你会看到警告
Argument "M" isn't numeric in numeric eq (==) at ...
Use of uninitialized value in numeric eq (==) at ...
Run Code Online (Sandbox Code Playgroud)
if子句在这里给出了误报,因为字符串'M'被转换为数字(0),因为数字相等运算符强加了上下文==.LHS值也是undef,它也被转换为数字(0),这就是表达式求值为真的原因.