Perl error in grepping array -
i have written sub procedure in perl check whether if string array contains particular value.
sub check_if_entity_exists() { $entity = shift; @entityarray = @_; print "my entity checked $entity \n"; print "entity array before change @entityarray : \n"; join(" ", map { s/^\s*|\s*$//g; $_ } @entityarray); print " array after change @entityarray \n"; $status = "false"; if (grep { $_ eq $entity } @entityarray) { $status = "true"; return $status; } else { return $status; } }
in above code @entityarray
= xyz.com $entity
= xyz.com since entity there in entity array expect set true flow going false
output log: entity checked xyz.com entity array before change xyz.com : array after change xyz.com
you have empty prototype check_if_entity_exists
subroutine. insists there must no parameters subroutine, wrong. should never use prototypes in perl - work differently prototyps in other langauges , meant specific.
you using map
in void context, , join
generates string discarded. should always have
use strict; use warnings;
at top of all programs, have told you
useless use of join in void context
and should write map
loop as
for (@entityarray) { s/^\s+//; s/\s+\z//; }
other that, code should me. if call this
my @entityarray = (' xyz.com '); $entity = 'xyz.com'; print check_if_entity_exists($entity, @entityarray);
output
my entity checked xyz.com entity array before change xyz.com : array after change xyz.com true
it better write using first
function list::util
, this
use list::util 'first'; sub check_if_entity_exists { $entity = shift; defined(first { /^\s*\q$entity\e\s*$/ } @_) ? 'true' : 'false'; }
Comments
Post a Comment