tags:

views:

85

answers:

3

I have been trying several regular expressions in the substitution operator:

$str =~ s/^0+(.)/$1/;

converts 0000 to 0 and 0001 to 1

$str =~ s/^0+./$1/;

converts 0000 to empty string, 000100 to 00, 0001100 to 100.

what difference is the parentheses making?

A: 

In case of first expression , the $1 has matched pattern .

In case of second expression , there will not be $1 variable , because it does not has any

grouping.

pavun_cool
+1 understood now
iamrohitbanga
+2  A: 

This seems like a bit of a misuse to me - you need the () to identify what's your match.

http://perldoc.perl.org/perlre.html

Capture buffers

The bracketing construct ( ... ) creates capture buffers. To refer to the current contents of a buffer later on, within the same pattern, use \1 for the first, \2 for the second, and so on. Outside the match use "$" instead of "\". (The \ notation works in certain circumstances outside the match. See the warning below about \1 vs $1 for details.) Referring back to another part of the match is called a backreference.

So basically you can use

if ($str =~ /^0+(.)/) { print "matched $1"; }

If you have more than one grouped matches they will be $1, $2, $3... etc e.g.

if ($str =~ /(0*)(1*)/) { print "I've got $1 and $2"; }

+2  A: 

If you want to get value in the $1 or $2 you need to group the pattern in the regular expression. Without grouping if you want to get the value, it will display error message, if you use the following statement.

use strict;
use warnings;

In the second statement, if you use the $1 variable without grouping. So that time the value of $1 will be empty. So it will replace the matched value into empty.

muruga