views:

105

answers:

3
#!/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?

+3  A: 

This pattern replacement is probably the most efficient solution:

$a =~ s/\b \b/_/g;
amphetamachine
agreed, it looks good ;--)
mirod
Please don't use `$a` or `$b` in examples unless it involves [sorting](http://perldoc.perl.org/perlvar.html).
Zaid
@Zaid - Good point, but I was just using the same variables as the OP.
amphetamachine
+5  A: 

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.

mirod
Please don't use `$a` or `$b` in examples unless it involves [sorting](http://perldoc.perl.org/perlvar.html).
Zaid
`$a` was used in the question (and in your answer!). For the spectators here, `$a` and `$b` are "predeclared" in Perl, so you can use it in sort routines under `strict`. I have never been sure why that made it bad to use them anywhere else though.
mirod
I see where you got the `$a` from, looks like Chas took care of it. And I could've sworn I used `$s`! ;)
Zaid
+2  A: 

This question wouldn't be complete without an answer involving explicit look-ahead and look-behind assertions:

$s =~ s/(?<=\w) (?=\w+)/_/g
  • This is effectively the same as the solutions involving the zero-width word-boundary anchor, \b.

  • Note that look-ahead regexes can match regexes of any character length, but look-behind regexes have to be of fixed-length (which is why (?<=\w+) can't be done).

Zaid
+1. I've never really used the look-ahead and look-behind assertions that much. Thanks.
Noufal Ibrahim