ashok13123 has asked for the wisdom of the Perl Monks concerning the following question:

HI all,
@arr1=qw(a b c d e sdf); $val1="http://www.google.com/home?sFocus=(sFocus.value)&sLis +t=(sList.value)"; push(@arr1,$val1); $val="sdf"; if(grep(/$val1/i,@arr1)) { print "Value is present\n" ; } else { print "Value is not present\n"; } if(grep(/$val/i,@arr1)) { print "Value is present\n" ; } else { print "Value is not present\n"; }
The first if statement will print the value is not present and the next will print Value is present....Why???How can i rectify it?????????

Replies are listed 'Best First'.
Re: Search for array element
by ikegami (Patriarch) on Jun 18, 2009 at 15:01 UTC
    Two problems
    • You want the search string to be matched character for characters, but the match operator expects a regex pattern. You need to convert it to a regex pattern using quotemeta or \Q..\E.
    • You check if the search string is contained in any string of the array. You seem to want to check if the search string is equal to any string of the array.

    Solution:

    grep /^\Q$search\E\z/i, @arr

    or

    $search = lc($search); grep lc($_) eq $search, @arr;
Re: Search for array element
by kennethk (Abbot) on Jun 18, 2009 at 14:56 UTC
    Your issue is that the contents of $val1 contain regular expression control characters and you expect them to be interpreted literally. Given your context, the easiest solution would be to have Perl escape the control characters using a \Q and \E pair, i.e.

    if(grep(/\Q$val1\E/i,@arr1))

    For more information, read up on String interpolation and Regular Expressions.

    Update: Upon a little further reflection, perhaps you mean

    if(grep($val1 =~ /$_/i,@arr1)) { print "Value is present\n" ; } else { print "Value is not present\n"; }