> -----Original Message-----
> From: Verhare [mailto:[EMAIL PROTECTED]]
> Sent: Monday, October 01, 2001 9:52 AM
> To: [EMAIL PROTECTED]
> Subject: Find and delete
> 
> 
> Hi,
> 
> I'm fairly new to perl and having a little problem.
> 
> I want to delete a word from a phrase.  My problem is that 
> the word is 
> contained in square brackets.  The phrase looks something like this :
> 
>     [Deletethis] And some other words
> 
> 
> I tried to use something like this to delete the word between (and 
> including) the brackets, but it doesn't work :
> 
>     my $phrase = "[Deletethis] And some other words";
>     my $wordtodelete = "[Deletethis];

There's a quote missing at the end of this line.

>     $phrase =~ s/$wordtodelete//;

The problem is that the square brackets indicate a character
class in a regular expression. The regex

   /[Deletethis]/

Will match a single character, one of D, e, l, t, h, i, or s.

In order to literally match a square bracket, you need to
escape it with a backslash:

   /\[Deletethis]/

Since your $wordtodelete may or may not include such "meta"
chars, the best way to do this is to use the \Q sequence in
your regex. This automatically escapes all following meta
chars in the regex, if any:

   /\Q$wordtodelete/

P.S., if you wanted to quote the bracket in your assignment
above, the following would NOT work:

   my $wordtodelete = "\[Deletethis];

because the double-quotes will "eat" the backslash and the
regex will still see /[Deletethis]/

You would either need to use:

   my $wordtodelete = '\[Deletethis]';

or

   my $wordtodelete = "\\[Deletethis";

In the first case, single quotes do not treat backslash as
special (except for \'). In the second case, the double quotes
interpret \\ as a single \

perldoc perlre

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to