in reply to find a string in an array of arrays
There are four problems with your code. First the $_ in the grep() is assigned to an arrayref, you need to dereference the ref to get at the first element of the inner array of your AoA:
second you are executing the grep() in a scalar context .. in that context it will return the number of items matched, not the item(s) themselves:my $GrepResult = grep($_->[0] =~ /$SearchStr/,@cdata);
third, the regexp would match even strings as 'not_the_test2.txt.gz':my ($GrepResult) = grep($_->[0] =~ /$SearchStr/,@cdata);
that is you want (I believe) to find only the exact matches not the first file that contains the search string.my ($GrepResult) = grep($_->[0] =~ /^$SearchStr$/,@cdata);
to make sure such characters are escaped. In that case, it's easier though to get rid of the regexp completely:my ($GrepResult) = grep($_->[0] =~ /^\Q$SearchStr\E$/,@cdata);
my ($GrepResult) = grep($_->[0] eq $SearchStr,@cdata);
If you did need a regexp and were looking for something not exact there is one more thing to notice. qr//. If you do
then the regexp is compiled again for each item in @data. This could be expensive, especially if $SearchStr was really a regexp and was complex. In that case it's good to do something likemy ($GrepResult) = grep($_->[0] =~ /^$SearchStr$/,@cdata);
This way the regexp is compiled just once and the search is quicker.my $regexp = qr/^$SearchStr$/; my ($GrepResult) = grep($_->[0] =~ $regexp,@cdata);
HTH, Jenda
|
Support Denmark! Defend the free world! |
|
|---|