How to replace consecutive spaces individually in perl

I want to replace every space in "a b" with "\" and the expected result is "a \ \ \ b".
I tried the following code but the result 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 fix this?

+4
source share
2 answers

Hmmm

$input = "a   b";

$input =~ s/\s/\\/g;

Tested and working, 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 well for you. The idea is that we match \ s and will do it again and again until your corresponding character is like \ s, space character regular expressions

+1
source

, , /g ( "global" ) .

alex@yuzu:~$ perl -E '$str = "a   b"; $str =~ s/ /\\ /g; say $str;'
a\ \ \ b

, , , , . quotemeta().

alex@yuzu:~$ perl -E '$str = q{a   b   ()+?$@%}; say quotemeta $str;'
a\ \ \ b\ \ \ \(\)\+\?\$\@\%

. perldoc quotemeta.

+1

Source: https://habr.com/ru/post/1529998/


All Articles