in reply to First Pattern Matching

One way to acheive your end, if you don't mind not knowing which pattern matched, but only need the keyword, would be to combine your patterns using the | (regex or operator) and remove the inner loop as here.

#!/usr/local/bin/perl -w use strict; my $str1 = 'ABCBXBCA'; my $str2 = 'APCBXBCAC'; my $patterns = 'B.B|CB'; foreach my $string ($str1,$str2){ # foreach my $pat (@patterns){ if($string =~ /$patterns/){ print "String:$string Pattern:$patterns KeyWor +d:$` \n";; # last; } # } } __DATA__ #ouptut C:\test>180890 String:ABCBXBCA Pattern:B.B|CB KeyWord:A String:APCBXBCAC Pattern:B.B|CB KeyWord:AP C:\test>

Update:Following jryan's post below, I thought I remembered a special var that would return the last match. Looking it up I found $+.

#!/usr/local/bin/perl -w use strict; my $str1 = 'ABCBXBCA'; my $str2 = 'APCBXBCAC'; my $patterns = 'B.B|CB'; foreach my $string ($str1,$str2){ # foreach my $pat (@patterns){ if($string =~ /($patterns)/) { print "String:$string Pattern:$+ KeyWord:$` \n +";; # last; } # } } __DATA__ #output C:\test>180890 String:ABCBXBCA Pattern:BCB KeyWord:A String:APCBXBCAC Pattern:CB KeyWord:AP C:\test>

Note the brackets in the if statement and the $+ in the print.

UpdateAs jryan notes below, this does still not completely match the requirements of the original question. I, nor anyone else it seems, had noticed that $+ returns the text matched not the pattern that matched it.

If you need to know which pattern matched, you will have to either use jryan solution from here or possibly look into using the scarey (to me at least) technique that hofmator doesn't suggest in the last if statement in this post. If you opt for the latter, you'd better takes a good look at some of japhys or abigail-II's posts as this level of regex is well beyond me at the moment.

Finally. Check perlman:perlre for dire warning regarding the performance hit of using $` which you already had, and $+ which I added.


Anyone know of an abbottoire going cheap?

Replies are listed 'Best First'.
Re: Re: First Pattern Matching
by jryan (Vicar) on Jul 11, 2002 at 22:00 UTC

    I just noticed that your answer is still incomplete. It only outputs the last match, and not the last pattern matched. For instance: BCB is not the same as B.B. You'll still have to do some sort of pattern lookup (such as I did below, or use something like Tie::Hash::Regex or Tie::Hash::Approx to construct a table and then match against that.