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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.