我在perl中编写了一个子过程来检查我的字符串数组是否包含特定值。
sub check_if_entity_exists() {
my $entity = shift;
my @entityarray = @_;
print "my entity to be checked $entity \n";
print "entity array before change @entityarray : \n";
join(" ", map { s/^\s*|\s*$//g; $_ } @entityarray);
print " array after change @entityarray \n";
my $status = "FALSE";
if (grep { $_ eq $entity } @entityarray) {
$status = "TRUE";
return $status;
}
else {
return $status;
}
}
在上面的代码中@entityarray
= xyz.com
$entity
= xyz.com
由于实体存在于实体数组中,我希望设置为true但流程将为false
输出日志: 我要检查的实体xyz.com 更改前的实体数组xyz.com: 更改后的数组xyz.com
答案 0 :(得分:3)
您的check_if_entity_exists
子例程有一个空原型。这坚持认为这个子程序必须没有参数,这是错误的。你应该从不在Perl中使用原型 - 它们的工作方式与其他语言中的原型不同,并且用于非常具体的事情。
您还在void上下文中使用map
,join
生成一个立即丢弃的字符串。您总是
use strict;
use warnings;
位于所有程序的顶部,可以告诉你
无效使用void上下文中的连接
您应该将map
循环写为
for (@entityarray) {
s/^\s+//;
s/\s+\z//;
}
除此之外,您的代码会为我做的事情。如果我这样称呼它
my @entityarray = (' xyz.com ');
my $entity = 'xyz.com';
print check_if_entity_exists($entity, @entityarray);
<强>输出强>
my entity to be checked xyz.com
entity array before change xyz.com :
array after change xyz.com
TRUE
最好使用first
中的List::Util
函数来编写此代码,就像这样
use List::Util 'first';
sub check_if_entity_exists {
my $entity = shift;
defined(first { /^\s*\Q$entity\E\s*$/ } @_) ? 'TRUE' : 'FALSE';
}