Reputation: 51
I want to replace every space in "a b" with "\ " and the expected output is "a\ \ \ b".
I have tried the following code but the output did not satisfy.
#!usr/bin/perl -w
use CGI;
my $q = CGI -> new;
print $q -> header();
$input = "a b";
(my $output = $input) =~ s/\ /\\ /;
the output is "a\ b" but not "a\ \ \ b".
How can I get it right?
Upvotes: 4
Views: 133
Reputation: 1570
First up, as a previous answerer has already mentioned, you're just missing the /g ("global") modifier on your substitution regular expression.
alex@yuzu:~$ perl -E '$str = "a b"; $str =~ s/ /\\ /g; say $str;'
a\ \ \ b
However going one step further, I wonder if you are looking to escape characters other than spaces. In that case you might want to look into using the quotemeta()
builtin.
alex@yuzu:~$ perl -E '$str = q{a b ()+?$@%}; say quotemeta $str;'
a\ \ \ b\ \ \ \(\)\+\?\$\@\%
For more information see perldoc quotemeta
.
Upvotes: 1
Reputation: 239
Hmmm
$input = "a b";
$input =~ s/\s/\\/g;
Tested and works, my test code
#!/usr/bin/perl
$abc = "a b";
$abc =~ s/\s/\\/g;
print $abc, "\n";
Cerberus:~ alexmac$ ./testaaa.pl
a\\\\\\\\\\b
This should work nicely for you. The idea is we are matching the \s and it will do it over and over until your matching any \s type character, the white space character set regular expressions
Upvotes: 1