On 3/10/09 Tue  Mar 10, 2009  8:19 AM, "howa" <howac...@gmail.com>
scribbled:

> Hello,
> 
> Consider the code:
> #===================
> 
> use strict;
> 
> my $a = 'a.jpg';
> 
> if ($a =~ /(html|jpg)/gi) {
>     print 'ok';
> }
> 
> #===================
> 
> 
> Is the brucket "()" must be needed? Since I am not using back
> reference, are there a better way?

No, the parentheses are not need in this simple case. The pattern
/html|jpg/i will work fine (you don't need the 'g' modifier since you are
only looking for one match).

However, if you want other elements in your pattern, you may need
parentheses to group sub-elements. For example, if you wanted to match only
if the 'html' or 'jpg' were at the end of the string, then /html|jpg$/ will
not work, as this pattern will match 'html' anywhere in the string. You will
have to use /html$|jpg$/ or /(html|jpg)$/. Non-capturing parentheses can be
used for clustering without capturing, as in /(?:html|jpg)$/.

You can make your regexs a little more readable with the 'x' modifier:

    / html | jpg /ix



 



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to