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).
In reply to Re: String comparison in an array
by haukex
in thread String comparison in an array
by newperlbie
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |