Actually, I'm not sure that iterating through the array is such a bad option, particularly if you're going to exit the loop after you find an element. If you use grep, you're going to look through all of the items in the array no matter what; what if the first element in the array matches, and you have 100 items? Then you're looking through 99 items when you don't need to. That's an exaggeration, but the point is the same.

The hash option is a good one, although not if you're actually looking through each item for regular expression matches--are you? It seems like you could be from your explanation, but I'm not absolutely sure that you are. In that case, you probably can't use a hash...

meaning that, in my opinion, your best option is to iterate through the array and check each element, then exit the loop once you've found a matching element.

my $itemPart = "Group1]Item2"; my @items = ( '[x.Group1]Item1=Value1', '[y.Group1]Item2=Value2', '[z.Group1]Item3=Value3', '[a.Group2]Item1=Value1', '[b.Group2]Item2=Value2' ); my $found_item; for my $item (@items) { # for each element, test if it contains $itemPart; # we need to use \Q and \E to meta-quote $itemPart, # in case it contains any regexp metacharacters if ($item =~ /\Q$itemPart\E/o) { $found_item = $item; last; } } # now check if we actually found an item; # if we did, $found_item will be defined if (defined $found_item) { print $found_item, "\n"; } else { print "Not Found!\n"; }
It's possible, of course, that you want *all* items that match in the array; in that case, use grep:
my @matching = grep /\Q$itemPart\E/o, @items;

In reply to Re: Can you scan an @array for a fragment of data? by btrott
in thread Can you scan an @array for a fragment of data? by ChuckularOne

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.