in reply to Re: Substitution for braces
in thread Substitution for braces

The actual program code is below:
Open FH,’file.txt’; while (<$FH>) { $arr[$i].="$_"; } close ($FH); $text=$arr[$i]; $text =~ /<cc>([\s\S]+?)<\/cc>/; $Name_pre=$1; $Name=$1; $Name=~ s/&amp;amp;/-/g; $Name=~ s/&amp;/-/g; $Name =~ s/-$//g; $st=$Name; $char=chop($st); if($char eq '-') {$Name=~ s/$//g;} $arr[$i]=~ s/$Name_pre/$Name/g;
Is it the right way of coding. When I execute the program with the $Name_pre as
fg-&amp;amp;&amp;+(and(we-
the program terminates giving an error at the line
$arr[$i]=~ s/$Name_pre/$Name/g;
as
Unmatched ( in regex; marked by <-- HERE in m/fg-&amp;amp;&amp;+(and( +<-- HERE we- /

Replies are listed 'Best First'.
Re^3: Substitution for braces
by GrandFather (Saint) on Jul 08, 2009 at 09:48 UTC

    There are many other problems in the script as presented, but you immediate problem can probably be solved by changing the offending line to:

    $arr[$i]=~ s/\Q$Name_pre\E/$Name/g;

    True laziness is hard work
      while(my $line=<DATA>){ if($line =~ /<cc>([\s\S]+?)<\/cc>/){ #print $name_pre; my $name=$1; my $name_pre = $1; $name=~ s/&amp;amp;/&amp;/g; $name=~ s/&amp;/-/g; $name =~ s/-$//; $name_pre=~ s/\Q$name_pre\E/\Q$name\E/g; $name_pre =~ s/\\//g; } } __DATA__ fg-&amp;amp;&amp;+(and(we- <id>6VE4AGAfg-&amp;amp;&amp;+(and(we-</id><cc>fg-&amp;amp;sonia&amp;-n +d_&amp;amp;lio_(we-</cc>
      These changes doesnot reflect on the file. The replace is not done for the files. Please tell me what is the solution
Re^3: Substitution for braces
by Utilitarian (Vicar) on Jul 08, 2009 at 10:17 UTC
    Take a look at perlre for more info and the opportunity to learn, but basically you'll either have to escape them using backslashes or use \Q \E to contain your $Name_pre string, though as pointed out above, why are you assigning the value in such an odd way?

    you could substitute all ( in a string with the regex $string =~ s/\(/$cheesesauce/g;

    Oh Goddess, look this code needs a lot of work, take a look at the following

    open($FH,'<','file.txt'); $arr[$i]=join('',(<$FH>)); close ($FH); $arr[i] =~ /<cc>([\s\S]+?)<\/cc>/$1/; $arr[i] =~ s/&amp;amp;/-/g; $arr[i] =~ s/&amp;/-/g; $arr[i] =~ s/\(/-/g; # I assume $arr[i] =~ s/-$//; if (substr($arr[i],-1,1) eq '-') { $arr[i]=~ s/-$//g; # I assume you meant, though you've already done + it above }
    I'm sure it's far from perfect, but an improvement on your current code nonetheless