why does the regrex do not work?

A

Amaninder

Hi everyone
I am new to perl and i am encountering a problem with regrex.
In the following code i want to delete "3)" from $string using $a. For
some reason it is giving me an error. Could any one know how to fix it?

#!/usr/bin/perl -w
use strict;

my $a = "3)";
my $string = "3) <MEM0__I__36__antenna36> - Programmed" ;

$string =~ s/$a// ;

print $string;

Regards
Amaninder Saini :)
 
P

Paul Lalli

Amaninder said:
Hi everyone
I am new to perl and i am encountering a problem with regrex.
In the following code i want to delete "3)" from $string using $a. For
some reason it is giving me an error.

Not just "an error", but a very specific error. Did you read the
error?

Unmatched ) in regex; marked by <-- HERE in m/3) <-- HERE /
Could any one know how to fix it?

#!/usr/bin/perl -w
use strict;

my $a = "3)";
my $string = "3) <MEM0__I__36__antenna36> - Programmed" ;

$string =~ s/$a// ;

print $string;

It's telling you that the ) in the regular expression is unmatched.
That is, Perl is assuming ) is a special character in your regular
expression. That is, as far as Perl is concerned, your regexp is:

$string =~ s/3)//;

Now, if you had written that, you would probably know that you need to
escape that parenthesis:

$string =~ s/3\)//;

Obviously, that's harder to do when your string is contained in a
variable. So instead, you simply use an escape sequence that says
"Escape any special character":

$string =~ s/\Q$a\E//;

\Q...\E will automatically backslash any special character that comes
between the \Q and \E, so that they match themselves, rather than
acting as RegExp meta-characters.

Hope this helps,
Paul Lalli
 
A

Amaninder

Chris said:
Paul has pretty much covered your problem, so I'll just add an
observed flaw in your code that isn't causing you problems
(yet). Don't use $a (or $b) as variable names; they're
used by Perl's sort functions.


Chris Mattern

Thanks a millions
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,200
Messages
2,571,046
Members
47,646
Latest member
xayaci5906

Latest Threads

Top