|
Posted by comp.llang.perl.moderated on March 20, 2008, 12:36 pm
Please log in for more thread options
> I have a somewhat strange requirement
> I want to find if a regex matched what exactly matched
>
> to reproduce this
>
> ------------------
> my @x;
> $x[0] = 'chi+ld*';
> $x[1] = '\sjoke';
>
> $_=getinput(); # for test assume $_="This is a joke";
>
> if(/($x[0]|$x[1])/){
> print "Matched '$1' \n";}
>
> -----------------
>
> I want to know if $x[0] matched or $x[1] matched
> What is the most efficient way of doing this ?
>
One way:
if ( / ($x[0]) | ($x[1]) /x ) {
print defined $1 ? "first" : "second";
}
But, this may be more efficient often:
if ( /$x[0]/ ) { print "first" }
elsif ( /$x[1]/) { print "second" }
Ordering alternatives with the most likely
matches in front can greatly increase efficiency
too.
--
Charles DeRykus
|