in reply to Can you scan an @array for a fragment of data?
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.
It's possible, of course, that you want *all* items that match in the array; in that case, use grep: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"; }
my @matching = grep /\Q$itemPart\E/o, @items;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: Re: Can you scan an @array for a fragment of data?
by ChuckularOne (Prior) on Apr 16, 2000 at 03:47 UTC |