tags:

views:

124

answers:

2
$a ="SCNSC:                                            [email protected]";
$b ="alerts:                                         nek";
$c ="daily-report:                           tasd,dfgd,fgdfg,dfgdf,[email protected]";

print "matched" if ($a =~ /\w+:\s*\w+@\w+\.\w+/ );
print "matched" if ($b =~ /\w+:\s*\w+[,\w+]{0,}/ );

 print "matched" if ($c =~ /\w+:\s*\w+[,\w+]{0,}/ );

its not displaying matched

+7  A: 

The -W warning option is your friend:

$ perl -W sample .pl
Possible unintended interpolation of @companay in string at junk.pl line 1.
Possible unintended interpolation of @dfs in string at junk.pl line 3.
Name "main::companay" used only once: possible typo at junk.pl line 1.
Name "main::dfs" used only once: possible typo at junk.pl line 3.

So $a and $c don't contain the literals @companay and @dfs they contain an empty (undefined) array interpolated in their place. The expression {0,} is equivalent to * (meaning zero or more) so let's clean that up and Perl has too much punctuation already so let's drop the unneeded parentheses. This gives us the only match Perl didn't warn us of:

print "matched" if $b =~ /\w+:\s*\w+[,\w+]*/ ;

which is fine except you probably meant to use grouping parenthesis as the last part of the regexp instead of "zero or more occurences of the character class containing , \w and +. Fixing all this yields:

$a ='SCNSC:    [email protected]';
$b ='alerts:      nek';
$c ='daily-report:  tasd,dfgd,fgdfg,dfgdf,[email protected]';

print "matched\n" if $a =~ /\w+:\s*\w+@\w+\.\w+/ ;
print "matched\n" if $b =~ /\w+:\s*\w+(,\w+)*/ ;
print "matched\n" if $c =~ /\w+:\s*\w+(,\w+)*/ ;

Which does match all strings. Note that \w does not include the character @ so they match, but maybe not precisely what you wanted.

msw
question changed ..
Tree
is there any thing wrong in the regular expression
Tree
answer changed, yes, the regexp was broken too
msw
+2  A: 

Always add use strict; and use warnings; at the top of your scripts.

It'll bring silly typos and the like to your attention.

Also, avoid using $a and $b for variable names, as these are especially reserved for the sort function.

Zaid