Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this substitution?

#!/usr/bin/perl

use strict;
use warnings;

my $s = "sad day
 Good day
 May be Bad Day 
 ";

$s =~ s/\w+ \w+/_/gm;

print $s;

I am trying to substitute all spaces between words with _, but it is not working. What is wrong with that?

like image 642
Tree Avatar asked Nov 26 '25 21:11

Tree


1 Answers

The substitution replaces an entire word (\w+) then a space then an other word by an underscore.

There is really no need to replace (or capture for what matters) those words

$a=~s/\b +\b/_/gm;

will replace a word break ( \b, a zero-width transition between a word and a non word) followed by one or more spaces followed by an other word break, by an underscore. Using \b ensures that you don't replace a space after or before a new line.

like image 55
mirod Avatar answered Nov 28 '25 11:11

mirod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!