----- Original Message ---- From: Ovid <[EMAIL PROTECTED]> To: Michael Alipio <[EMAIL PROTECTED]> Sent: Sunday, January 21, 2007 4:49:41 PM Subject: Re: putting ";" as a replacement in the substitution.
--- Michael Alipio <[EMAIL PROTECTED]> wrote: > Hi, > > #I have this string: > > my $string = 'vd=root,status='; > > #Now, I want to transform it into: > > 'vd=root;status=' > > #That is replace the comma(,) between root and status with semicolon > (;); > > $string =~ s/vd=\w+(,)/;/; > print $string,"\n"; > > #And it prints: > > ;status= > > Can you tell me why it has ate up vd= as well? > And how to get around with it.. > Try: > $string =~ s/(vd=\w+),/$1;/; > The parentheses are for capturing a match and the 'dollar digit' > variables are for accessing the results of whatever the parentheses > captured. However, when using a substitution (s///), the left hand > side is the regex to match text and the right hand side is what you > replace the entire *match* with. > So your substitution "vd=\w+(,)" was matching "vd=root,", capturing the > comma, ignoring said capture (since you weren't using $1), and then > replacing the entire match with ';'. It did work but this is quite confusing. As far as I can understand, parenthesis in regexp are used to indicate whatever you are looking for. and if I am going to do something like: s/(vd=\w+),/$1;/; $1 should contain only "vd=\w+" and not including the ",". So as I understand it, the expression above will result to replacing "vd=\w+" with "vd=root;," my $string = 'devid=234FG,vd=root,status=ok,logid=235'; print "There is an alphanumeric word at the beginning that is followed by a =\n" if $string =~ /^(\w+)=/; print "My first match contains $1\n"; print "My entire match contains $&\n"; See, in my first match, given the regexp(\w+) which is surrounded by ( ), it captures "devid" And goes without saying the entire match consist of "devid" and "=". Now, in substitutions: my $string = 'devid=234FG,vd=root,status=ok,logid=235'; $string =~ s/(vd=\w+),/$1;/; print "My first match is $1\n"; print "My entire match is $&\n"; How come my $1 which contains only "vd=root" when replaced with "vd=root;", the comma in the regexp pattern was also included in $1?? > See 'perldoc perlre' for more information. > Cheers, > Ovid -- Buy the book -- http://www.oreilly.com/catalog/perlhks/ Perl and CGI -- http://users.easystreet.com/ovid/cgi_course/ ____________________________________________________________________________________ The fish are biting. Get more visitors on your site using Yahoo! Search Marketing. http://searchmarketing.yahoo.com/arp/sponsoredsearch_v2.php