1

I'm trying to shorten all multiple spaces to one space, except for the first occurence of spaces (indentation).

I've found that this code will replace the first occurences:

$_ =~ s/^ +/ /;

So I thought, its negation will do what I want. But it does not:

$_ =~ s/!^ +/ /g;

What am I doing wrong?

lmocsi
  • 550
  • 2
  • 17

2 Answers2

2

You can change approach to the regex

s/\S\K +/ /g;
mpapec
  • 50,217
  • 8
  • 67
  • 127
1

Exclamation mark is not negation in regex. At least, not like that.

What you need is negative lookbehind:

s/(?<!^)\s+/ /g;

Should do the trick.

Sobrique
  • 52,974
  • 7
  • 60
  • 101