Trap of matching by string variable in Perl

  When you want to match a continuous string by string variable, just append parenthesises between variable!

use 5.010 ;


$_ = 'ababababab1212abab12abab' ;
$var = 'ab' ;

m
/^$var+/ ; # m/^ab+/ : mismatch
say 'm/^$var+/' ;
say
'$` = '.$` ;
say
'$& = '.$& ;
say
'$\' = '.$' ;

say
'---------' ;

m/^($var+)/ ; # m/^ab+/ : mismatch
say
'm/^($var+)/' ;
say
'$` = '.$` ;
say
'$& = '.$& ;
say
'$\' = '.$' ;

say
'---------' ;

m/^($var)+/ ; # m/^(ab)+/ : ok
say
'm/^($var)+/' ;
say
'$` = '.$` ;
say
'$& = '.$& ;
say
'$\' = '.$' ;

say
'---------' ;

m/^(ab)+/ ; # m/^(ab)+/ : ok
say
'm/^(ab)+/' ;
say
'$` = '.$` ;
say
'$& = '.$& ;
say
'$\' = '.$' ;


  

posted @ 2011-08-24 21:38  walfud  阅读(139)  评论(0编辑  收藏  举报