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:

my $GrepResult = grep($_->[0] =~ /$SearchStr/,@cdata);
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.
Which leads to the last problem, the $SearchStr might contain some special characters ... actually it already does, the dot. The dot means "any character" within a regexp. So you would need
my ($GrepResult) = grep($_->[0] =~ /^\Q$SearchStr\E$/,@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] 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

my ($GrepResult) = grep($_->[0] =~ /^$SearchStr$/,@cdata);
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 like
my $regexp = qr/^$SearchStr$/; my ($GrepResult) = grep($_->[0] =~ $regexp,@cdata);
This way the regexp is compiled just once and the search is quicker.


In reply to Re: find a string in an array of arrays by Jenda
in thread find a string in an array of arrays by jgatrell42

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.