perl – 来自哪个错误“使用未初始化的值在字符串ne”?
发布时间:2020-12-15 22:02:18 所属栏目:大数据 来源:网络整理
导读:the below code的未初始化值在哪里? #!/usr/bin/perluse warnings;my @sites = (undef,"a","b");my $sitecount = 1;my $url;while (($url = $sites[$sitecount]) ne undef) { $sitecount++;} 输出: Use of uninitialized value in string ne at t.pl line
the below code的未初始化值在哪里?
#!/usr/bin/perl use warnings; my @sites = (undef,"a","b"); my $sitecount = 1; my $url; while (($url = $sites[$sitecount]) ne undef) { $sitecount++; } 输出: Use of uninitialized value in string ne at t.pl line 6. Use of uninitialized value in string ne at t.pl line 6. Use of uninitialized value in string ne at t.pl line 6. Use of uninitialized value in string ne at t.pl line 6. 解决方法
您不能在没有警告的字符串比较中使用undef.
if ("a" ne undef) { ... } 会发出警告.如果要测试变量是否被定义,请使用: if (defined $var) { ... } 关于原始问题的评论: 这是一个奇怪的方式来迭代一个数组.更常见的做法是: foreach my $url (@sites) { ... } 并将$sitecount变量完全删除,并且不要在循环体中覆盖$url.也删除该数组中的undef值.如果您不想因某种原因(或期望未定义的值插入到该位置)来删除该undef,则可以执行以下操作: foreach my $url (@sites) { next unless defined $url; ... } 如果您想要使用循环构造的形式测试未定义,则需要: while (defined $sites[$sitecount]) { my $url = $sites[$sitecount]; ... $sitecount++; } 以避免警告,但要注意自动化,如果在其他活动值之间存在undefs,则循环将停止. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |