in reply to String comparison in an array

grep { $elements[0] eq '$_' }@keys
is it something to do with string comparison with quotes and no quotes?

Yes, because single quotes don't interpolate variables - '$_' means "the string consisting of the two characters $ and _". "$_" would interpolate the variable into the string. Note that if @keys contains only strings, you can just say grep { $elements[0] eq $_ } @keys, without the quotes.

Also, note that grepping an array like this is usually less efficient than using a hash. For example, you can say my %keyhash = map {($_=>1)} @keys; and this will create a hash where the keys are the elements of the @keys array, and the values are all 1. Then, to check if an element is contained in @keys/%keyhash, you just need to say if ($keyhash{$elements[0]}) ....

Update: The trick with creating a hash that makes it more efficient is of course to only do it once, above any loops. Also, as a side note, there is first from List::Util, that is like grep but stops when it finds the first match (but depending on the data it's likely still slower than a hash).

Replies are listed 'Best First'.
Re^2: String comparison in an array
by newperlbie (Acolyte) on Aug 08, 2018 at 12:55 UTC
    sure,thanks,but with hash too the comparison is not working, probably because $element[0] is coming with double quotes "computer" and the strings in the array/hash do not.....how to get rid of this, this is coming from the split statement

      It seems you can simply add double quotes around computer, or you can remove double quotes around "computer";