Reputation: 5247
I have written a sub procedure in perl to check whether if my string array contains a particular value.
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;
}
}
In the above code @entityarray
= xyz.com
$entity
= xyz.com
Since entity is there in entity array i expect to set to true but flow is going to false
Output log: my entity to be checked xyz.com entity array before change xyz.com : array after change xyz.com
Upvotes: 0
Views: 103
Reputation: 126762
You have an empty prototype for your check_if_entity_exists
subroutine. That insists that there must be no parameters to this subroutine, which is wrong. You should never use prototypes in Perl - they work differently from prototyps in other langauges and are meant for something very specific.
You are also using map
in void context, and join
generates a string that is immediately discarded. You should always have
use strict;
use warnings;
at the top of all your programs, which would have told you
Useless use of join in void context
And you should write the map
loop as
for (@entityarray) {
s/^\s+//;
s/\s+\z//;
}
Other than that, your code does what it should for me. If I call it like this
my @entityarray = (' xyz.com ');
my $entity = 'xyz.com';
print check_if_entity_exists($entity, @entityarray);
output
my entity to be checked xyz.com
entity array before change xyz.com :
array after change xyz.com
TRUE
It would be better to write this using the first
function from List::Util
, like this
use List::Util 'first';
sub check_if_entity_exists {
my $entity = shift;
defined(first { /^\s*\Q$entity\E\s*$/ } @_) ? 'TRUE' : 'FALSE';
}
Upvotes: 3