Gossamer Forum
Home : General : Perl Programming :

Search and replace using tr//c

Quote Reply
Search and replace using tr//c
I've been playing around with this bit, but can't quite seem to get the last part right.

$checkit = "tony!|bob&sue|me@me.com";

$checkit =~ tr/[A-Za-z0-9][ ][.][|]/\*/c;

I've got it matching all non-character, non-numeric (except for space, period and pipe).

I want to replace the non-items with a backslash and the non-item. (tony\!|bob\&sue|me\@me.com).

I can't seem to figure out what to use where the * is in the tr// bit. I tried $1 (and about 6 million other things) but that didn't work.

Any suggestions?

Last edited by:

Watts: Dec 15, 2003, 2:11 PM
Quote Reply
Re: [Watts] Search and replace using tr//c In reply to
You probably want a substitution for that.

Is this what you need?

Code:
$checkit =~ s/([^\w\s.|])/\\$1/g; # The double backslash is intended.
Quote Reply
Re: [Coombes.] Search and replace using tr//c In reply to
Yep. That's it. It works.

I was (am) also confused by the ^ character apparently it can be used as "not" and it can be used as "starts with". Crazy Correct me if I'm wrong.

Okay, here's my take on what is happening with s///g:

$checkit =~ s/([^\w\s.|])/\\$1/g;

s/ = substitue
([ ]) = a range of items
^ = that is not
\w = any alpha-numeric character A-Z, 0-9
\s = or whitespace (spaces for the most part)
. = or period
| = or pipe
/ = with
\\ = a backslash
$1 = and the item being replaced
/g = and do it (globally) for each occurance you find.
Quote Reply
Re: [Watts] Search and replace using tr//c In reply to
Yep you are correct.

^ will match the beginning of a string if used like so:

$string =~ /^something/;

...or the beginning of a line in a multi-line string, if you use /m, eg:

$string =~ /^abc/m;

[^ ...] however is a negated character class. Meaning anything *other* than what you specify, will be matched.

Last edited by:

Coombes..: Dec 16, 2003, 8:56 AM