in reply to Re^2: Finding out which of a list of patterns matched
in thread Finding out which of a list of patterns matched
The unasked question here is: Once you have the match, how will you determine what action to take?
If you are reading the patterns to be matched from a separate file prepared by someone else, how do they indicate what action should be taken? Or how do you decide what action should be taken for each pattern matched?
could be arbitrarily complex - ... I don't think the matching text will be much good for a key to a hash.
The matching text may not be a good key as it wouldn't match a hash key that was a non-constant regex, but using $#- will tell you which pattern was matched, and could be used as an index to an array containing the original patterns to retrieve the one that matched (rather than the text it matched).
Eg.
my @patterns = slurp( 'file' ); my %dispatch; @dispatch{ @patterns } = ( ??? ); my $regex = '(', join( ')|(', @patterns ) . ')'; while( my $data = <DATA> ) { if( $data =~ $regex ) { $dispatch{ $patterns[ $#- ] }->( $1 ); } }
The problem with the above code is what to substitute for '???'. Ie. What action is required for matches against each pattern. But that problem exists whether you are using a dispatch table; an if/else cascade or any other mechanism. Of the choices available the dispatch table is by far the easiest--if not the only--option for the dynamic search patterns you describe.
|
|---|