[thelist] Re: str_replace equivalent in Perl?

Chris Nicholls evolt at axe.dircon.co.uk
Fri Feb 20 08:16:25 CST 2004


> Is there an equivalent of PHP's str_replace function in perl? 

This sort of thing is done in Perl using regular expressions. Regexes 
(as they are often referred to) are core to getting the most out of 
Perl. FWIW, I believe you can also use them in PHP.

To subsitute the text in your example:

 > str_replace ("+", " ", $variable_name);

do this:

$variable_name =~ s/\+/ /g;

Broken down that means "substitute '+' with ' ', for all instances it 
appears, in the variable $variable_name.

The '=~' means 'feed $variable_name into the Substitution Engine', as it 
were.

The 's' then tells Perl we're doing a substitution.

It then looks for whatever is between the first / / (\+) and replaces it 
with whatever there is in the second / /, ie a space.

The backslash before the plus sign (\+)  tells Perl to treat the 
character as a literal plus sign; plus signs otherwise have a special 
meaning in regexes.

And the final 'g' tells Perl to do the substitution Globally, ie as many 
times as possible.

'perldoc perlre' from the command line should give you some starters on 
regexes.

The O'Reilly books 'Learning Perl' and 'Programming Perl' are the 
classic manuals. The Perl Black Book (pub. Coriolis) is also very good.

Good luck

-Chris



More information about the thelist mailing list