Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string substitution

Status
Not open for further replies.

zzzqqq

Programmer
Oct 12, 2005
17
IE
Hi,
Anyone know is it possible to replace certain characters in a string with nothing?
Tried: $variable =~ tr/\t\+\"\?//, but doesn't work.
This does work: $variable =~ tr/\t\+\"\?/ /, but replaces with characters with spaces. Any ideas?
Cheers,
Mark.
 
Hello Mark,

I would do this with a regular expression substitution rather than with tr. Like this:
Code:
#always
use strict;
use warnings;

#declare and populate a string (a scalar)
my $var = 'abcdefg';

# have a look at it
print $var,"\n";

# do the substitution
$var =~ s/bc//g;

# have a look at it again
print $var,"\n";

Mike

You cannot really appreciate Dilbert unless you've read it in the
original Klingon.

Want great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Try this:
Code:
$variable =~ tr/\t\+\"\?//d;
or better:
Code:
$variable =~ tr/\t+"?//d;


Trojan.
 
Mike,

I think you'll find that "tr" will be faster than a regex for literal character deletion in a string. Also your code does not do what was asked, it deletes the compelte string "bc" and not the individual characters of tab, plus, double quote and question mark. To get the same thing with a regex would require alternation or better still a character class so if you benchmark them, make sure you test like for like.


Trojan.
 
Quite so - it was the principle I was talking about really. I don't use tr largely because it's a copy of the UNIX command of the same name. It's actually implemented in the same way as s///

Mike

You cannot really appreciate Dilbert unless you've read it in the
original Klingon.

Want great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top